Im looking a way to get an element id by a partial inner html
For exemple, I have this template
<div id="unpredictable-id1">
<label>
<span id="unpredictable-id1"> (unpredictable text) </span> <!-- this span have has the same id than div but has unpredictable content -->
<span>persistant text</span> <!-- this span have no id, no class, no identifier -->
</label>
</div>
I cant guess the <div> id (no suffix, no prefix, no other attributes ...)
the only way I have to get the element is by a text in an inner span (a text that I can find before)
I've tried thing like identifiers = document.querySelectorAll("[textContent*='persistant text']").id; but always return 'undefined'
Does anyone have a lead?
If you can get a reference to a descendant element, then you can use the .closest() method:
// Get all the span elements and loop through them
document.querySelectorAll("span").forEach(function(element){
// Check the textContent of the element for a match
if(element.textContent === "persistant text"){
// Find the nearest ancestor div
let closest = element.closest("div")
// ...then do whatever you want with it
console.log("The " + closest.nodeName + " has an id of: " + closest.id);
}
});
<div id="unpredictable-id1">
<label>
<span id="unpredictable-id1"> (unpredictable text) </span> <!-- this span have has the same id than div but has unpredictable content -->
<span>persistant text</span> <!-- this span have no id, no class, no identifier -->
</label>
</div>
FYI: ID's must be unique within a document. Having two elements with the same ID is invalid HTML and defeats the purpose of having IDs in the first place.
Also, [textContent*='persistant text'] didn't work because when you pass something inside of [] into querySelector() or querySelectorAll() you are indicating that you are searching for an attribute of an HTML element. textContent is not an attribute of an HTML element, it's a property of a DOM Element Node. So, nothing matched your search and therefore, you got undefined back.
Related
For example, if I have
<div>
<h2>Name</h2>
<h3>age</h3>
<span class='fa fa-trash'></span>
</div>
and when clicking the span (icon) I say
this.parentNode.childNodes[1].innerText
it would target the Name but if I say
this.parentNode.childNodes[2].innerText
it would not target Age. why is this? Is there a resource that explains this well? I know the indexing doesn't start at 0 but I don't understand how the indexing work.
DOM is not just the elements you see in your HTML code. In-between each element is a "text node" where text can be displayed. An example of this would be having text in a div below a a header. So...
<div>
<!-- Index 0: Text node -->
<h1>Header Text</h1> <!-- Index 1: Element -->
Description Text <!-- Index 2: Text node -->
</div>
As you can see, you are allowed to insert text in the div without wrapping it in an element. These are called text nodes which you see when you put the text in normal text elements (such as span or p) or buttons (<button>TEXT</button>). So to get around this in you JavaScript code, you could either do it the lazy way;
document.getElementById("ELEMENT_ID").childNodes[INDEX*2 + 1]
or by using the children property;
document.getElementById("ELEMENT_ID").children[INDEX]
The problem with this method is that it only returns 'element' children within the div, so the description text in the above HTML example will not be accessible. ([H1] instead of [Text, H1, Text]), but I suppose that is what you're looking for anyway. :)
I have an HTML like this
<div class="this">
EXP
</div>
I want to add id to <a>. But do not know what to do.
First select your element using something like .getElementsByClassName(). Keep in mind that .getElementsByClassName() returns a NodeList collection of elements, so you'll want to access the first index (or loop over them). You can then simply set the ID with .id, as the ID is merely a property of an element.
This can be seen in the following:
const element = document.getElementsByClassName('this')[0];
element.id = 'element';
console.log(element);
<div class="this">
EXP
</div>
If you want to add this with Javascript, you'll need to use a selector to target your <a> tag and then set the id attribute on it. You can do this by using the querySelector() function or as seen below:
// Find an <a> tag that occurs below a class called "this" and set its id attribute
document.querySelector('.this > a').id = "some-id";
There are many other available functions to handle this through native Javascript and other frameworks, so your milage may vary depending on what you are using.
Example
In this example, we have provided some CSS that should only apply to an element with an id of "test" and we'll run the necessary code to show that the id is being added to the element (as it will be red):
document.querySelector('.this > a').id = 'test';
#test { color: red; }
<div class="this">
EXP
</div>
Add the id attribute to the <a> tag. See the differences of the middle line:
<div class="this">
<a id="expid" href="exp.com">EXP</a>
</div>
I have prepended one div inside some div with many others:
<div class="content">
<div>sss</div>
<div>aaa</div>
<div>bbb</div>
</div>
I added <div>ddd</div> before sss with:
$('.content').prepend('<div></div>');
And when I want to append some new element to new prepended div it add's it as text:
$('.content>div')[0].append('<p>ddd</p>');
If I remove [0] it works but it appends to all divs, I need that [0] to find first div.
To get the first element (that is still a jquery object) you can use .first():
$('.content>div').first().append($('<p>ddd</p>'));
Note that I also wrapped the <p> with $(...) to make it a valid html element (and not text).
I need to know how i can add some javascript to add value inside text like below
The original div in HTML code like
<div> Text </div>
I need the some way to put an value inside the div appear in source like below
<div data-texe> Text </div>
I have try but its new for me
<script>
var div = document.getElementByDIV;
div.innerDIV += 'data-texe';
</script>
You want to set attribute?
var div = document.getElementById('yourid');
div.setAttribute('data','texe')
You will need to first find a way to identify your <div> elements, either with a unique ID or a class name. In this example I chose a unique ID:
<div id="test">Text</div>
If you want to add your data-texe attribute to all <div>s, you could use document.getElementsByTagName() and then loop over the results.
But let's stick to altering just one element for this example:
<script type="text/javascript">
// getElementByDIV is obviously not a valid function, so let's use
// one that finds an element by its ID:
var div = document.getElementById('test');
// The setAttribute function lets you add an attribute to the element
// The first parameter is the attribute name and the second is its value
// Attributes with no values are implicitly defined as empty string
div.setAttribute('data-texe', '');
</script>
Suppose I have two p tags in the document. I want to call two different effects using jQuery when onMouseOver event happens. Is it necessary that these two p tags be given Ids. Can't it be achieved without giving Ids to these tags ?
You don't have to give anything an id, however it is the best way to uniquely identify an element.
You can instead idenfity by class:
$(".myClass")
By attribute:
$("[src='image.jpg']")
By position in parent:
$("p:eq(2)")
A full list of selectors is available in the documentation
$('p:first'); // first p tag
$('p:last'); // last p tag
$('p').eq(1); // exactly the second p tag
There are several ways to select an element / elements:
$('.classname')
$('#id')
$('tagname')
$('[attr="value"]')
etc
although jQuery allows you to write faster and easier scripts, but unfortunately it makes you never understand the real JavaScript.
$("*") //selects all elements.
$(":animated") //selects all elements that are currently animated.
$(":button") //selects all button elements and input elements with type="button".
$(":odd") //selects even elements.
$(":odd") //selects odd elements.$("p") selects all <p> elements.
$("p.intro") //selects all <p> elements with class="intro".
$("p#intro") //selects the first <p> elements with id="intro".
$(this) //Current HTML element
$("p#intro:first") //The first <p> element with id="intro"
$("p:eq(2)") // The third <p> element in the DOM
$(".intro") //All elements with class="intro"
$("#intro") //The first element with id="intro"
$("ul li:first") //The first <li> element of the first <ul>
$("ul li:first-child") //The first <li> element of every <ul>
$("[href]") //All elements with an href attribute
$("[href$='.jpg']") //All elements with an href attribute that ends with ".jpg"
$("[href='#']") //All elements with an href value equal to "#"
$("[href!='#']") //All elements with an href value NOT equal to "#"
$("div#intro .head") //All elements with class="head" inside a <div> element with id="intro"
jQuery – Select element cheat sheet