jQuery find element with class name which is added dynamically - javascript

I have a navigation which is listed dynamically with PHP.
<nav id='navs'>
#foreach($element as $val)
<a data-prop={{$val->id}}>$val->name</a>
#endforeach
</nav>
The html :
The highlighted the tags are listed dynamically
I have a JS script, when we click on the navbar element then we add .selected class to the tag.
When the page is loaded the first tag has .selected class.
I need a JS code to find the data-prop attribute value for the elements with .selected class.
I tried:
var d= $("#navs .selected").attr('data-prop');
but the d variable is undefined. Any suggestion? I also tried the .find() method.

For the given example one could to the following:
first get an array of all related elements
d = $("#navs > a");
And then iterate and get your desired attributes:
for (index = 0; index < d.length; ++index) {
console.log(d[index].getAttribute("id"));
}
... the given example prints the ID attribute instead your custom attribute (data-prop)

I figured out what the problem was. I have a script which is adding the class name .selected to the tags, the problem is that it executed AFTER my script, where I wanted to find the element with the .selected class.
So my code is working:
var d= $("#navs .selected").attr('data-prop');

Related

How to target or change ancher or its id text color, if id changing randomly on page load

I am trying to changing anchor, id, span or b tag text color, but it's not changing because of randomly changing id.
Here is the HTML Code:
<a id="XgP7Wrq-1503732157576" tabindex="-1" href="javascript:void(0);" style=""><span class="thin">here</span> <b>sometext</b></a>
Here is the JS Code:
var x = getElementsbyid("XgP7Wrq-1503732157576");
x.style.color = '#00FF00';
else if any alternative way to achieve this?
Thanks
If you are traversing the DOM with ID, the correct syntax is as follows,
var x = document.getElementById("XgP7Wrq-1503732157576");
x.style.color = "#00FF00";
You do not include the hashtag as argument because the method specifically looks for the ID.
Since the ID of the elements is always changing, you may do one of the followings too.
// Accessing the third <a> element
var x = document.getElementsByTagName("a")[2]
// Accessing the first element with class "apple"
var x = document.getElementsByClassName("apple")[0]
Try using the class
<a id="XgP7Wrq-1503732157576" class="myclass" tabindex="-1" href="javascript:void(0);" style=""><span class="thin">here</span> <b>sometext</b></a>
Code js:
var x = document.getElementsByClassName("myclass");
//for first anchor
x[0].style.color = "#00FF00";
//for all
for(var i=0; i<= x.length; i++)
{
x[i].style.color = "#00FF00";
}
You'll have to find some other way to identify it, based on something that doesn't change. You haven't given us enough information for us to help you do that, but some ways are
Where it is in the structure of the page, a compound selector could find it. For instance, if it were the first a element with href="javascript:void(0)" that's inside a div with class header, then document.querySelector("div.header a[href='javascript:void(0)']") would find it. Or if that span.thin is consistent, then document.querySelector("a > span.thing").parentNode.
If there's something about the id that doesn't change, an attribute substring selector could work (document.querySelector("a[href*='substring']")).
If it's always the 4th (or whatever) a element with href="javascript:void(0)", you could find it based on that (document.querySelectorAll("a[href*='javascript:void(0)']")[3]).
...etc. The tools are:
document.getElementById - But you'd have to know its id, so that's out.
document.querySelector - Find the first element that matches the given CSS selector. Can be a full selector, including a compound one. Any valid CSS selector works.
document.querySelectorAll - Finds all elements that match the given CSS selector (as a list).

change href value on page load without adding classes

I am trying to overwrite an old link that is written into some code via a CMS, therefore I cannot access the base code easily.
I am trying to add a script that will overwrite the current link with a new one.
Here is my code:
script:
function linkChange() {
var links = document.getElementById("titlecontent");
links.getElementsByTagName("a").href = "http://www.cnn.com/";
}
or
function linkChange() {
document.getElementById("titlecontent").getElementsByTagName("a").href = "http://www.cnn.com/";
}
html:
<ul id="titlecontent"><li>link</li></ul>
The main issue is I cannot go in and add an id or class to the <a> tag, so I need to target it starting with the <ul> which has the id "titlecontent".
This works :
document.getElementById("titlecontent").getElementsByTagName("a")[0].href = "http://www.cnn.com/";
<ul id="titlecontent"><li>link</li></ul>
The problem was that you needed to select a specific element in getElementsByTagName, because it returns a list of elements, not just one.

How to get an element by its data-itemindex?

Suppose I want to get innerHTML of below <li> by its data-itemindex. i even don't know it is possible or not.
<li id="li:90" class="liGrid" data-itemindex="3" data-itemid="li:90" >
winoria</li>
i tried
alert($("li").find("[data-itemindex=3]").html());
alert($("li[data-itemindex='3']").text());
from How to select elements with jQuery that have a certain value in a data attribute array
but doesnt help me.
Use the CSS tag selector to locate the matching element/s within the DOM:
$("[data-itemindex=3]")
You can even do some more advanced selectors using a similar syntax:
[title~=flower] /* Selects all elements with a title attribute containing the word "flower" */
[lang|=en] /* Selects all elements with a lang attribute value starting with "en" */
a[src$=".pdf"] /* Selects every <a> element whose src attribute value ends with ".pdf" */
a[src^="https"] /* Selects every <a> element whose src attribute value begins with "https" */
Full documentation.
You can use:
$('li[data-itemindex="3"]').text();
or
$('li[data-itemindex="3"]').html()
Working Demo
Try This:
var data = $('li').data('itemindex', 3).text();
alert(data);

Javascript to get elements by their attributes

<body>
<span someAttribute="xyz">.....</span>
...
<div>
...
<span someAttribute="abc">.....</span>
...
<div someAttribute="pqr">.....</div>
...
</div>
</body>
Here is a sample html page.. I need to select the html elements by its attributes i can get the attribute values by getAttribute() but i need to select all the elements first.
How in javascript to get elements which has the attribute name as "someAttribute". Once i get the elements i can get the attribute values and use my function.
Note: i want to do this without using jquery.
In new browsers you can do:
var el = document.querySelector('[someAttribute="someValue"]');
store each element in a array the loop throught each element, and if the element contains the attribute someAttribute do somgthing.
var arr_elms = [];
arr_elms = document.body.getElementsByTagName("*");
var elms_len = arr_elms.length;
for (var i = 0; i < elms_len; i++) {
if(arr_elms[i].getAttribute("someAttribute") != null){
alert("FOUND : " + arr_elms[i].getAttribute("someAttribute"));
}
}
You can select elements by tag name using document.body.getElementsByTagName("div") to get all the div elements inside your document. This function returns an array of elements, which you can parse and filter out elements that don't match your criteria.
You can traver all elements of DOM tree.
you can use
var all = document.getElementsByTagName('*');
but this also returns the html, head and body ...
and then do a loop over all elements and look for the attributes.
I found a snippet called getElementsByAttribute(doc, tagArray, attribute, attributeValue)
You can give a try to a working fiddle: http://jsfiddle.net/Yx7EU/
Hope this can help.

remove div without an id tag

I need a solution to remove a div without an ID tag in JavaScript only. The div looks like this <div align="center">.
Here is the full structure.
<tr id="-1">
<td class="stxt">
<div align="center">
</div>
</td>
</tr>
You need to work out how to get a reference to it, once you've done that, you can remove it using:
div.parentNode.removeChild(div);
Of course the align attribute has been deprecated, but anyway, you can find the divs with align="center" using:
var divs = document.getElementsByTagName('div');
var div;
var i = divs.length;
while (i--) {
div = divs[i];
if (div.getAttribute('align') == 'center') {
div.parentNode.removeChild(div);
}
}
Which will remove every div in the document that has align="center".
Note that the object returned by getElementsByTagName is a NodeList. If you iterate over it from 0 and remove nodes, they are removed from the live list so you will skip the node following the one you remove and you will attempt to access no existant nodes at the end. Going over the list backwards avoids these pitfalls. An alternative is to turn the NodeList into an array, but that's somewhat inefficient.
Edit
Since you edited the question, here's an update answer.
You can get a reference to the TR using getElementById:
var root = document.getElementById('-1');
Now you can go down the DOM:
var cell = root.cells[0]; // First cell in the row
var div = cell.getElementsByTagName('div')[0]; // first div
cell.removeChild(div);
Which is specific to the structure you've posted.
If you can just remove the content, you can use:
var all = document.getElementsByTagName("div");
for(i=0; i < all.length; i++) {
all[i].innerHTML = ""
}
See http://jsfiddle.net/7KVkC/
You need some way to make this div tag unique. There is another javascipt function called getElementsByTagName that you can use to get an array of all of the div tags. You can then use the DOM to check whether that div tag has the property of align="center".

Categories

Resources