I am attempting to insert a new dom element after every 5 p tags but I cant get it to perform the insert. It is inserting at the end of the document. The page I am inserting into has 50+ p tags so I am not sure what I am doing wrong. Any help would be great. Here is what I am using:
$body = $this->get_body_node();
// Build our amp-ad tag
$ad_node = AMP_DOM_Utils::create_node( $this->dom, 'amp-ad', array(
'width' => 300,
'height' => 250,
'type' => 'ad',
'data-ad-client' => '###',
'data-ad-slot' => '###'
) );
// Add a placeholder to show while loading
$fallback_node = AMP_DOM_Utils::create_node( $this->dom, 'amp-img', array(
'placeholder' => '',
'layout' => 'fill',
'src' => 'https://placehold.it/300X250',
) );
$ad_node->appendChild( $fallback_node );
$p_nodes = $body->getElementsByTagName( 'p' );
$pListLength = $p_nodes->length;
if ( $pListLength > 5 ) {
for($i=5; $i <= $pListLength; $i+=5) {
$p_nodes->item($i)->parentNode->insertBefore( $ad_node, $p_nodes->item($i));
}
}