How to getElementByID in a specific DIV block (JS or JQUery) - javascript

I just wanted a fast/easy/simple way to check for existing ID on a specific element (div in this case)..
Can't seem to find code sample for this..im using jquery but i dont think i need to do jquery on this one, just basic getElement.. but i need to isolate the search inside a div block.. because the id does exist in other elements on the page but i need to know if it exist in a specific area/div.
so instead of just
document.getElementById(target_id);
i need something like:
divName.getElementById(target_id);
or
$("document.divName").getElementById(target_id);
or
$(".divName").document.getElementById(target_id);
Can't seem to find something that works.

IDs are supposed to be unique and no two elements in page should have same id. You may search some element with some class in div with specific ID.
$('#divId .someClass')
or using find()
$('#divId').find('.someClass')
or using context, jQuery( selector [, context ] )
$('.someClass', $('#divId'))

var mySubDiv = myParentDiv.querySelector("#mySubDivId")
is equivalent to
var mySubDiv = document.querySelector("#myParentDivId #mySubDivId");
// don't forget the space : #myParentDiv#mySubDivId won't work
where querySelector and querySelectorAll are very useful functions, enough for me to avoid using jQuery : they accept any css selector
in real life, using the same Id for different DOM elements often happens.

id's should be unique, you can check for element using:
$(".your_parent_div").find("div#some_unique_id");

you can use it for the getElementsByTagName or ClassName, but ID is unique over document. so doesn't need to do that. better to use a special ID.
and in every id define as a element in javascript and you can just write id's name and use it, like this :
ID.style.color = red;

According to my understanding on your question, You have used two id's with same name when u execute, It takes only first ID so you are asking to take id from the specific div, well that is bad type of coding to use two id for same name instead go for class if want to use same name.
solution for your question is -this ->
var someDiv = document.getElementsByClassName("divName");
var someId = someDiv[0].getElementById("target_id");

Related

Liferay set the id of liferay-ui:search-container-row

I want to set the id of the tr that is the result of the tag liferay-ui:search-container-row, how can I do it?
For Example, the resulting table row is:
<tr id="aui_3_4_0_1_350" class="portlet-section-header results-header">
I want to attach some javascript for the resulting table and I need something to refer to the various table row, like id="aui_3_4_0_1_350".
I could also use the class selector, but I don't know how to set it.
It is not posible to set a customized id value to a search-container-row. Because they get generated based on the input list and Ids need to be unique. However you can access it using a selector starting with the search-container itself. It depends on what you are trying to accomplish.
If you're using jQuery or similar it should be easy since there's a good variety of them: https://api.jquery.com/category/selectors/
If you want to give an element an id you should do it with setAttribute
For example, you first need to get a reference to the element that you want to give the id, with:
var id = document.querySelector("p").setAttribute("id", "idName");
if this is what you're looking for.

Ajax, filter div by id.

I have problem with filter more identic id in the same page.
document.getElementById(val1).innerHTML=xmlhttp.responseText;
I have three the same <div id="name"></div> on one page. And only first div display content. I try with jQuery and filter... but I dont have progress.
The id selector is something to return one unique element (or none if not found). That's why you shouldn't use multiple ids - it will always return [at most] only one (the first).
Fix that fault by using classes or something.
If you really have to get multiple elements with the same id, you can do by using an attribute selector:
$('[id="name"]').html(xmlhttp.responseText);
// or
[].forEach(document.querySelectorAll('[id="name"]'), function(el) {
el.innerHTML = xmlhttp.responseText;
});
document.getElementById
return only first element that having the specified ID. Id should always be unique.
You can try with other attributes like class and then use
document.getElementsByClassName("myClass")
that will return all the elements of given class.
ids should be unique. You shouldn't have two or more elements on the same page with the same id. You can use class names to identify them, and those can definitely be the same. I don't know your code, but try using document.getElementsByClassName (not supported in IE8), or using jQuery to simplify what you are trying to do: $('.my_class_name').html(xmlhttp.responseText)

Trying to getElementById from Walmart.com

I am really new to JavaScript, and Im basically trying to build a simple Script to get information from a site like Walmart.com. Im using firebug to test my little snippets. Im having a problem getting the price.
This is the my code:
var price = document.getElementById('clearfix camelPrice');
console.log(price);
I also tried ".camelPrice" with out the period and I keep getting null.
Thanks a lot in advance!
In this case, you're using the wrong method. getElementById does exactly what it says, it gets an element by its id. Looking on Walmart.com, 'camelPrice' is a CSS class.
We can still get elements by a class. What you want is document.getElementsByClassName(). Further, you can pass multiple arguments to getElementsByClassName like so:
document.getElementsByClassName('clearfix', 'camelPrice');
This grabs all elements that have both the clearfix and camelPrice classes set.
In addition to what the others have said about your selection looking like ids, here is how you can select by class name:
document.getElementsByClassName('classname');
Newer browsers allow you to make jQuery-like selections from native JavaScript:
document.querySelectorAll('#id .classname');
http://caniuse.com/queryselector
It looks like you're trying to provide a class selector to getElementById instead of an ID selector. This is what an ID looks like:
<div id="some-id">...</div>
This is what a class looks like:
<div class="some-class">...</div>
The difference is that only one element should ever have a specific ID on a page, where many elements might have the same class.
I am not sure how you are running your JavaScript in Walmart's site, which is not impossible, but maybe you should specify it, for instance if the Walmart site is in an iframe you will not be able to use getElementById() from your site.
On the other hand if you are running some sort of local Live Editor/Console, then maybe it is possible.
For the script you show above, you have an error on the ID since an id can only be one word, and you are missing to select what type of attribute you want from the element:
For example, <input>:
var price = document.getElementById('id').value
or for other tags like <div>:
var price = document.getElementById('id').innerHTML

How can I access a particular div on a page which has the same id in two places?

This is the same question as this:
Referring to a div inside a div with the same ID as another inside another
except for one thing.
The reason there are two elements with the same ID is because I'm adding rows to a table, and I'm doing that by making a hidden div with the contents of the row as a template. I make a new div, copy the innerhtml of the template to my new div, and then I just want to edit bits of it, but all the bits have the same ID as the template.
I could dynamically create the row element by element but it's a VERY complex row, and there's only a few things that need to be changed, so it's a lot easier to just copy from a template and change the few things I need to.
So how do I refer to the elements in my copy, rather than the template?
I don't want to mess up the template itself, or I'll never be able to get at the bits for a second use.
Or is there another simpler way to solve the problem?
It will probably just be easiest when manipulating the innerHtml to do a replace on the IDs for that row. Maybe something like...
var copiedRow = templateRow.innerHTML.replace(/id=/g,"$1copy")
This will make the copied divs be prefixed with "copy". You can develop this further for the case that you have multiple copies by keeping a counter and adding that count variable to the replace() call.
When you want to make a template and use it multiple times its best to make it of DOM, in a documentFragment for example.
That way it doesn't respond to document.getElementById() calls in the "live" DOM.
I made an example here: http://jsfiddle.net/PM5544/MXHRr/
id's should be unique on the page.
PM5544...
In reality, there's no use to change the ID to something unique, even though your document may not be valid.
Browsers' selector engines treat IDs pretty much the same as class names. Thus, you may use
document.querySelector('#myCopy #idToLookFor');
to get the copy.
IDs on a page are supposed to be unique, even when you clone them from a template.
If you dynamically create content on your page, then you must change the id of your newly cloned elements to something else. If you want to access all cloned elements, but not the template, you can add a class to them, so you can refer to all elements with that class:
var clonedElement = template.cloneNode(yes); // make a deep copy
clonedElement.setAttribute("id", "somethingElse"); // change the id
clonedElement.setAttribute("class",
clonedElement.getAttribute("class") + " cloned"
);
To access all cloned elements by classname, you can use the getElementsByClassName method (available in newer browsers) or look at this answer for a more in-depth solution: How to getElementByClass instead of GetElementById with Javascript?
Alternatively, if you have jQuery available, you can do this is far less lines of code:
$("#template").clone().attr("id","somethingElse")
.addClass("cloned").appendTo("#someDiv");
The class lookup is even simpler:
$(".cloned").doSomethingWithTheseElements();
Try to avoid using IDs in the child elements of the cloned structure, as all ids of the cloned element should be changed before adding the clone to the page. Instead, you can refer to the parent element using the new id and traverse the rest of the structure using classnames. Class names do not need to be unique, so you can just leave them as they are.
If you really must use ID's (or unique "name" attributes in form fields), I can strongly suggest using a framework like jQuery or Prototype to handle the DOM traversal; otherwise, it is quite a burden to resolve all the cross-browser issues. Here is an example of some changes deeper in the structure, using jQuery:
$("#template").clone().attr("id","somethingElse")
.addClass("cloned") // add a cloned class to the top element
.find("#foo").attr("id","bar").end() // find and modify a child element
.appendTo("#someDiv"); // finally, add the node to the page
Check out my ugly but functional cheese. I wrote a function that works like getelementbyid, but you give it a start node instead of the document. Works like a charm. It may be inefficient but I have great faith in the microprocessors running today's browsers' javascript engines.
function getelement(node, findid)
{
if (node)
if (node.id)
if (node.id == findid)
return node;
node = node.firstChild;
while(node)
{
var r = getelement(node, findid);
if (r != null)
return r;
node = node.nextSibling;
}
return null;
}
When you copy the row, don't you end up having a reference to it? At that point can't you change the ID?

Using jQuery to delete all elements with a given id

I have a form with several spans with id="myid". I'd like to be able to remove all elements with this id from the DOM, and I think jQuery is the best way to do it. I figured out how to use the $.remove() method to remove one instance of this id, by simply doing:
$('#myid').remove()
but of course that only removes the first instance of myid. How do I iterate over ALL instances of myid and remove them all? I thought the jQuery $.each() method might be the way, but I can't figure out the syntax to iterate over all instances of myid and remove them all.
If there's a clean way to do this with regular JS (not using jQuery) I'm open to that too. Maybe the problem is that id's are supposed to be unique (i.e. you're not supposed to have multiple elements with id="myid")?
.remove() should remove all of them. I think the problem is that you're using an ID. There's only supposed to be one HTML element with a particular ID on the page, so jQuery is optimizing and not searching for them all. Use a class instead.
All your elements should have a unique IDs, so there should not be more than one element with #myid
An "id" is a unique identifier. Each time this attribute is used in a document it must have a different value. If you are using this attribute as a hook for style sheets it may be more appropriate to use classes (which group elements) than id (which are used to identify exactly one element).
Neverthless, try this:
$("span[id=myid]").remove();
id of DOM element shout be unique. Use class instead (<span class='myclass'>).
To remove all span with this class:
$('.myclass').remove()
if you want to remove all elements with matching ID parts, for example:
<span id='myID_123'>
<span id='myID_456'>
<span id='myID_789'>
try this:
$("span[id*=myID]").remove();
don't forget the '*' - this will remove them all at once - cheers
Working Demo
The cleanest way to do it is by using html5 selectors api, specifically querySelectorAll().
var contentToRemove = document.querySelectorAll("#myid");
$(contentToRemove).remove();
The querySelectorAll() function returns an array of dom elements matching a specific id. Once you have assigned the returned array to a var, then you can pass it as an argument to jquery remove().
You should be using a class for multiple elements as an id is meant to be only a single element. To answer your question on the .each() syntax though, this is what it would look like:
$('#myID').each(function() {
$(this).remove();
});
Official jQuery documentation here.
As already said, only one element can have a specific ID. Use classes instead. Here is jQuery-free version to remove the nodes:
var form = document.getElementById('your-form-id');
var spans = form.getElementsByTagName('span');
for(var i = spans.length; i--;) {
var span = spans[i];
if(span.className.match(/\btheclass\b/)) {
span.parentNode.removeChild(span);
}
}
getElementsByTagName is the most cross-browser-compatible method that can be used here. getElementsByClassName would be much better, but is not supported by Internet Explorer <= IE 8.
Working Demo

Categories