I am using a function that obtains a target element id at onclick. Example, if I click on the text element that has the id of 'help'.
var click = (e && e.target) || (event && event.srcElement);
The var click would contain the ref to the id of "help".
I want to compare the var click to the string 'help' using the if statement below.
if (click == 'about') {do something}
The comparison does not work because the var click is not a string. When I use the alert(click) to debug, it shows click as "object HTMLElement".
How would you compare whether the id 'help' is obtained from var click?
I could write out something like
if (click == document.getElementById('help')) {do something}
but that would make a long statement.
also
if the var click is document.getElementById('help'), how would I create a new var "div" as document.getElementById('helpdiv') by adding the word "div" in the id of the var click?
basically, I want to use the same function to generate dynamic responses to each element that was clicked on, and not having to create a separate function for each element.
if (click.id == 'help'){
var link = click;
var divid = click.id+'div';
var div = document.getElementById(divid);
alert (div.id); //helpdiv string
}
TIA for all your help.
The simplest approach is probably
if (click.id == 'help') { //do something }
The line:
var click = (e && e.target) || (event && event.srcElement);
is not getting the id rather the element itself, use getAttribute to get the id instead.
var id = click.getAttribute('id');
alert(id);
Or simply:
var id = click.id;
alert(id);
So your condition now becomes:
if (id == 'about') {do something}
and
if (id == document.getElementById('help')) {do something}
if (click["id"] != null && click["id"] == "help") { do stuff }
Addressing the last part of your question, you cannot create a new DOM object by modifying your current one like you propose in your question, and I do not understand if you want to locate an already existing object and store it in a variable, or create a new one from scratch, so :
If you want to find a new one, and you know its named like "show" + the id of your current click variable, you can easily do:
if (click["id"] != null) {
var found = document.getElementById("show" + click["id"]);
}
Or if you intend to create a new one :
if (click["id"] != null) {
var created = document.createElement("div"); // replace with whatever you need
created["id"] = "show" + click["id"];
}
I think this is what you're after ...
if (click.id == 'help') { // Test to see if click is the 'help' element
var newEl = document.createElement('div'); // Create a new element
newEl.id = click.id + 'div'; // Set it's id
newEl.innerHTML = 'my help text goes here'; // Set it's content
click.parentElement.appendChild(newEl); // Add it to the document immediately following the 'click' element
}
Be aware that the name of an element is not the same as the element itself. Just making a new element name by appending 'div' to some existing name does not, in and of itself, create a new element. You have to explicitely create a new element object and add it into the document, as shown above.
Related
I have tried to lookup for an answer to this but I have not been able to find an answer.
In my project, I add HTML by using JS.
let winnerHTML = 'this HTML will appear in the dom when a condition is met'
const gameCont = document.getElementById('game-container');
const decideWinner = () => {
if ( spadesPosition === 90 ||
heartsPosition === 90 ||
clubsPosition === 90 ||
diamondsPosition === 90 ) {
gameCont.insertAdjacentHTML("afterend", winnerHTML);
}
};
Now I want to remove that HTML, I've tried to set winnerHTML = ''; but clearly it's not the right logic. Since the added HTML is not part of the document, I can't select it and remove it.
Could you guys help me out here? My apologies in advance if there's already something about this but I didn't find it.
Cheers!
Add it to paragraph or span with id for later reference :
let winnerHTML = "<p id='para'>this html will appear in the dom when a condition is met<p>";
Then to remove it:
let elem=document.getElementById("para");
elem.remove();
You can also use document.createElement and store the element in a variable. Then you can use the remove function to remove it. Example
let elem = document.createElement("p");
elem.innerHTML = "Your text";
document.getElementById('game-container').appendChild(elem);
elem.remove();
I want to check if some html element contains three classes, or some of them containts another two with different names.
How can I do that in JavaScript?
If there is not something pure js, then jquery suggestions are welcomed.
I tried matches, but that checks some of them not all
With contains that doesn't work too to check if all of them are on that element :S
for(let i = 0;i < allButtons.length;i++)
{
if(allButtons[i].matches('.forwardButton,try') && allButtons[i].disabled == false)
{
// // alert("b")
// if(objectWithSameOrderWhenTheyAreAnswered[`arrayWithSameOrderWhenTheyAreAnswered${answersCounter}`].length != 4)
// {
// objectWithSameOrderWhenTheyAreAnswered[`arrayWithSameOrderWhenTheyAreAnswered${answersCounter}`].push(answers[i])
// }
}
Try the following:
var el = document.getElementsByTagName('div')[0];
console.log(el.classList.contains('class2'));
console.log(el.classList.contains('class3'));
<div class="class1 class2 class4"></div>
I know how to find specific text, but I'm really struggling to find elements with specific text
for example: <span class="foo">Special</span>
Is there example like this script below to find elemements with text?
var txt = window.document.body.innerHTML;
if (txt.match(/Special/)) {
// do something if true
alert("Found");
} else {
// do something if false
alert("Sorry");
};
You could e.g. catch every element inside your document and check if any of them contains given text.
var elems = document.querySelectorAll("*"),
res = Array.from(elems).find(v => v.textContent == 'Special');
console.log(res ? 'found!' : 'not found');
<span class="foo">Special</span>
<span class="foo">Else</span>
With pure Javascript just grab element's parent like this:
var x = this.parentElement.nodeName; //x=="span"
or
var x = this.parentElement; //x == <span> object
With jQuery just grab element's parent like this:
$(this).parents("span");
So if you add above line inside your if you can get span element as object or as text.
HI i am working in Javascript.
My code is:
var oldData = document.getElementById(id).innerHTML;
alert(oldData);
alert is shown as : text<img src="add-icon.png"><div id = "1"></div>
Here old data contains a text an image tag and a div tag. The issue is I want to just access the div tag id but i dnt know how to get it. Please help.
Thanx in advance
The thing with using vanilla JavaScript is, you've got to write all the filters yourself :)
var oldData = document.getElementById(id), firstDiv, id;
firstDiv = filterElements(node);
id = firstDiv.id;
function filterElements( node ){
var children = parent.childElements, firstDiv, node;
for (var i = 0; i < children.length; i += 1 ){
node = children[i];
if (node.tagName && node.nodeType && node.nodeType === 1 &&
node.tagName.toLowerCase() === "div"){
firstDiv = node;
break;
}
}
return firstDiv;
}
I suggest the use of jQuery. Then you can access the id of the div within its element stored as elem as
$(elem).children("div").attr("id")
If you know the parent by ID, then you can do this:
$("#"+id).children("div").attr("id")
or even this:
$("#"+id+">div").attr("id")
Of course, if you want the ID just to access an element, then you don't need to. To append a new image to the div:
$("#"+id+">div").append("<img ...>")
or
$("#"+id+">div").append($("<img>"). ...)
Also, I recommend using classes instead of childhood to identify elements:
$("#"+id+" .image-holder").append(...)
or
$("#"+id+").find(".image-holder").append(...)
I am trying to see how to find a tag that was added dynamically within a table as so:
ParentTag= document.getElementById('parentdiv');
var newTag = document.createElement('div');
newTag.innerHTML="<span class="ImNew"></span>"
ParentTag.appendChild(newTag);
How will I be able to find that tag in javascript, not leaning towards using jquery so no live recommendations please.. Trying to find that new tag in strictly javascript.
The tag I am referring to is the span tag
You could give your new tag an ID when you create it:
ParentTag= document.getElementById('parentdiv');
var newTag = document.createElement('div');
newTag.setAttribute('id','myNewID');
newTag.innerHTML="<span class="ImNew"></span>"
ParentTag.appendChild(newTag);
Then later, just use that ID to find it:
var newTag = document.getElementById('myNewID');
That depends on what other elements exist in the element. You can for example get all span tags in the element and filter out the ones with a specific class name:
var parentTag = document.getElementById('parentdiv');
var spans = parentTag.getElementsByTagname('SPAN');
var filtered = [];
for (var i=0; i<spans.length; i++) {
if (spans[i].className === 'ImNew') filtered.push(spans[i]);
}
If there is only one span tag with that class name in the element, the filtered array now cotnains a reference to that element.
As others have mentioned, why not just keep track of it or give it an id if you're going to need it later?
But anyway, this is how you could do a manual search (searching from back to front as you're adding the new items to the end).
var parent = document.getElementById("parentdiv")
for (var i = parent.childNodes.length - 1; i >= 0; i--)
{
var el = parent.childNodes[i];
if (el.nodeType == 1 &&
el.nodeName.toLowerCase() == "div" &&
el.firstChild &&
el.firstChild.nodeName.toLowerCase() == "span" &&
el.firstChild.className = "ImNew")
{
// el.firstChild is what you want
}
}