Grabbing innerHTML into a variable

144 Views Asked by At

I am trying to grab the text in a p tag into a variable. The p tag is called #musCardImageTitle and is a description of the background image on that page. However, it's not working. I dont know why

var desc = document.getElementById("musCardImageTitle").innerHTML;
document.getElementById("sb_form_q").placeholder = desc

//the second line is putting that text into a searchbox as placeholder text

This is for the Bing homepage if it helps. I've included an image of what I'm trying to do if it helps

https://i.stack.imgur.com/bJeU8.jpg

I think this should be easy but for some reason I cant get it to work...

2

There are 2 best solutions below

2
On BEST ANSWER

Try this one

// select the target node
var target = document.querySelector('#musCardImageTitle');

// create an observer instance
var observer = new MutationObserver(function(mutations) {
    mutations.forEach(function(mutation) {

        //document.getElementById("sb_form_q").value = mutation.target.textContent ;
        document.getElementById("sb_form_q").placeholder = mutation.target.textContent;
        observer.disconnect();

    });
});

// configuration of the observer:
var config = { attributes: true, childList: true, characterData: true };

// pass in the target node, as well as the observer options
observer.observe(target, config);

This example is on MutationObserver doc

1
On

Try this

var desc = document.getElementById("musCardImageTitle").value;