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
http://i.stack.imgur.com/bJeU8.jpg
I think this should be easy but for some reason I cant get it to work...
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
Try this
var desc = document.getElementById("musCardImageTitle").value;
Related
This is my code.
var hitButton = document.querySelector('.btn-hit');
var scoreResults = document.querySelectorAll(".flex-blackjack-row-1 h3");
var scores = document.querySelector(".flex-blackjack-row-1 span");
const config = {childList: true};
const bustedMessage = document.createElement('h2');
bustedMessage.textContent = 'BUSTED!';
const busted = function (mutationList, observer){
if (parseInt(scores.textContent) > 21) {
console.log(scores.textContent)
scoreResults[0].before(bustedMessage);
hitButton.setAttribute('disabled', 'true');
}
}
const observer = new MutationObserver(busted);
observer.observe(scores, config);
In that callback function named "busted", I'm adding an attribute to "hitButton". But when I try to update it like this in another function
hitButton.setAttribute('disabled', 'false');
it is not being updated.
But I can remove that attribute using
hitButton.removeAttribute('disabled');
Removing that attribute is doing what I want to do. But now I need to know, why can not I update it instead of removing?
Because, these attributes in HTML tags are just boolean attributes. Say for e.g., if "disabled" attribute is present, it tells the browser to disable it regardless of the value you are setting to it.
"checked", "disabled", "selected", "muted", "autoplay", "loop", "controls" are some of the boolean attributes in HTML.
Google "Boolean attributes in HTML". You will learn more about it. Hope it answers your question.
I am trying to retrieve the old position value of a div element on a page using the Mutation Observer. This is the code that I have:
var mutationObserver = new MutationObserver(callback);
var target = document.getElementById('test');
var config = {
attributes : true,
childList : false,
subtree : false,
attributeOldValue : true,
};
mutationObserver.observe(target, config)
function test (){
var target = document.getElementById('test');
target.style.backgroundColor = "black"
}
function callback(mutations, mutationObs){
for (var i = 0; i < mutations.length ; i++){
var mutation = mutations [i];
alert(mutation.oldValue)
}
}
When the color of my test div changes, I get an alert with all the old style attribute value.
Alert : "position: relative; top:40px;"
Is there a way to only use the top value for example?
Thank you!
You can split you string and get what you need.
var alertValueSplit = mutation.oldValue.split("top:")
var topValue = alertValueSplit[1]
I have a dynamic web form, I'd like to detect if an element is visible; and if it is hide another element of mine. I have the below attempt, but this is not working stabilily; i.e. the element isn't always hiding. A better technique out there?
setInterval( myValidateFunction2, 1000);
function myValidateFunction2 () {
var inElgbl = document.getElementById('field_52_116');
if (typeof(inElgbl) != 'undefined' && inElgbl != null)
{
document.getElementById('field_52_24').style.display = "none";
}
};
It is by default display: none; but may become display: block; if it becomes display: block; I would like to display: none; my other div elem.
Consider an element to be visible if it consumes space in the document. For most purposes, this is exactly what you want.
Try this:
setInterval( myValidateFunction2, 1000);
function myValidateFunction2 () {
var inElgbl = document.getElementById('field_52_116');
if (inElgbl.offsetWidth <= 0 && inElgbl.offsetHeight <= 0)
{
document.getElementById('field_52_24').style.display = "none";
}
};
Probably the most stable way to do this would be using a DOM Mutation Observer and setting it up to watch the document or section of the document that could get the element in question.
In the example below, I'll set up an observer to watch an initially empty div and after I've set it up, I'll dynamically add the element we're supposed to be on the lookout for. You'll see that the element does not wind up getting displayed.
// Select the node that will be observed for mutations
var targetNode = document.getElementById('parent');
// Options for the observer (which mutations to observe)
var config = { attributes: true, childList: true, subtree: true };
// Callback function to execute when mutations are observed
function callback(mutationsList, observer) {
// We only need to test to see if node is truthy, which it will be if it exists
if (document.getElementById('field_52_116')){
document.getElementById('field_52_24').style.display = "none";
console.log("Node detected! Removing....");
}
};
// Create an observer instance linked to the callback function
var observer = new MutationObserver(callback);
// Start observing the target node for configured mutations
observer.observe(targetNode, config);
// So, we'll add the node to test
let newNode = document.createElement("div");
newNode.textContent = "I'm here so the other node should be hidden!";
newNode.id = "field_52_116";
targetNode.appendChild(newNode);
// Later, you can stop observing if needed
// observer.disconnect();
<div id="parent"></div>
<div id='field_52_24'>ELement to hide</div>
I am in need of a way to detect if any DOM Node/Element has been removed or modified and instantly restore that element to the state in which it was before.
I tried to "backup" the body node and set the body.innerHTML to its original state every time MutationObserver is fired after the first run but that crashes the browser.
Is there any fast way to restore elements that have been modified or removed?
This is all I can come with (a bit hacky, but it works). Click test or test #2 for removing nodes: http://codepen.io/zvona/pen/BowXaN?editors=001
HTML:
<div class='preserve'>
<h1>There can be anything inside this</h1>
<p>Some content</p>
</div>
<div class='preserve'>
<p>Some more content</p>
</div>
JS:
var preserved = document.querySelectorAll('.preserve');
var config = { attributes: true, childList: true, characterData: true };
var createFragment = function(elem, i) {
var frag = document.createElement('div');
var id = 'id-'+ new Date().getTime() +'-'+ i;
frag.setAttribute('id', id);
elem.parentNode.insertBefore(frag, elem);
elem.dataset.frag = id;
observer.observe(elem.parentNode, config);
}
var observer = new MutationObserver(function(mutations) {
mutations.forEach(function(mutation) {
if (!mutation.addedNodes.length && mutation.removedNodes.length) {
Array.prototype.forEach.call(mutation.removedNodes, function(elem) {
var frag = document.querySelector('#'+ elem.dataset.frag);
frag.parentNode.replaceChild(elem, frag);
createFragment(elem, frag.id.split('-')[2]);
});
}
});
});
Array.prototype.forEach.call(preserved, function(preserve, i) {
createFragment(preserve, i);
});
If you want to preserve all the nodes (aka document.querySelectorAll('*');), then I think it becomes very heavy from performance point of view.
The problem is to record the removed nodes.
In my case, I generate a xpath for every nodes in the document. When childList triggered, generate again.
So that I can know the removed node's xpath, and can use the xpath to restore the node.
mutation.removedNodes.map((node) => {
const xpath = node.xpath // which is generated each time `childList` triggered
})
Hope to help you.
Is it possible to change an element's inner HTML before it is inserted in the DOM?
I already tried doing this with MutationObserver but the problem is that you can see the element's HTML visually changing, is there a way to do this before DOM insertion altogether?
var observer = new MutationObserver(function(mutations) {
mutations.forEach(function(mutation) {
mutation.addedNodes[0].innerHTML = "....";
});
});
// Notify me of everything!
var observerConfig = {
attributes: true,
childList: true,
characterData: true
};
var targetNode = document.querySelector("ul#myElement");
observer.observe(targetNode, observerConfig);
You can try having the whole body as CSS display:none, change whatever you want and then bring it back to display:block