将innerHTML抓取到变量中

时间:2014-11-26 12:25:51

标签: javascript html firefox greasemonkey userscripts

我试图将p标签中的文本抓取到变量中。 p标记称为#musCardImageTitle,是该页面上背景图像的描述。但是,它不起作用。我不知道为什么

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

如果有帮助,这是Bing主页。如果有帮助的话,我已经包含了我想要做的图像

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

我认为这应该很容易,但由于某些原因我无法让它发挥作用......

2 个答案:

答案 0 :(得分:1)

试试这个

// 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);

此示例位于MutationObserver doc

答案 1 :(得分:0)

试试这个

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