JQuery Selector Selecting Selectively - javascript

I have the following HTML
<i class="up_icon" id="1" />
<p class="position">1</p>
<i class="down_icon" id="1" />
I can select .up_icon#1 but not .down_icon#1
var u = $(".up_icon#1"); //= [<i class=​"up_icon" id=​"1">​</i>​]
var d = $(".down_icon#1"); //= []
What am I missing here?

You should not duplicate ID like that. ID should be unique across document.
In your case you can use jQuery attribute selector function. See below,
<i class="up_icon" data-id="1"/>
<p class="position">1</p>
<i class="down_icon" data-id="1"/>
And then you can access them by .up_icon[data-id=1] and .down_icon[data-id=1]

You should NEVER assign the same ID to several tags
Also:
From the HTML specification:
ID and NAME tokens must begin with a letter ([A-Za-z]) and may be
followed by any number of letters, digits ([0-9]), hyphens ("-"),
underscores ("_"), colons (":"), and periods (".").

can select .up_icon#1 but not .down_icon#1
This is due to the fact that duplicate Ids are invalid HTML and throw off the selector.
jQuery requires you to have unique IDs across your page or you will experience unexpected behaviours.
Taken from jQuery id selector documentation
Each id value must be used only once within a document. If more than
one element has been assigned the same ID, queries that use that ID
will only select the first matched element in the DOM. This behavior
should not be relied on, however; a document with more than one
element using the same ID is invalid.
Change your HTML to:
<i class="up_icon" id="1" />
<p class="position">1</p>
<i class="down_icon" id="2" />
Now you can select .up_icon#1 or .down_icon#2.
Obviously if you can find a way to apply more descriptive identifiers, other than plain numbers, to keep anything from repeating the better.
You could also use optional data-attributes data-value="1" to store any sequence or record id if needed. jQuery selectors have no issues with same values in data-attributes or classes.

You should switch you class and id definitions. Try this instead:
<i id="up_icon" class="1" />
<p class="position">1</p>
<i id="down_icon" class="1" />
var u = $("#up_icon.1");
var d = $("#down_icon.1");

Related

Why am I unable to get the value of this input field using jQuery?

I've been trying to figure out what's wrong with my code for a while now, and why it won't let me get the value of my input field.
My code looks like this:
<script src="https://code.jquery.com/jquery-3.1.0.js"></script>
<input type=text id="0.1.2_00_1" value=0>
<script>
console.log($('#0.1.2_00_1').val())
</script>
Why doesn't this work? Hopefully I'm not just being really dumb.
If an ID carries a period (special character) in jquery you must escape it like so with double slashes:
console.log($('#0\\.1\\.2_00_1').val());
You need to escape the periods. For example $('#0\\.1\\.2_00_1')
<script src="https://code.jquery.com/jquery-3.1.0.js"></script>
<input type=text id="0.1.2_00_1" value=0>
<script>
console.log($('#0\\.1\\.2_00_1').val())
</script>
As the jQuery docs on selectors state:
To use any of the meta-characters ( such as
!"#$%&'()*+,./:;<=>?#[\]^{|}~ ) as a literal part of a name, it must
be escaped with with two backslashes: \\.
The id contains the . character which, when passed to a JQuery selector, is interpreted as a CSS class qualifier.
It's causing JQuery to look for an element who's id is 0 that uses a CSS class of 1 and another called 2_00_1.
The official spec. says:
"Using characters except ASCII letters, digits, '_', '-' and '.' may
cause compatibility problems, as they weren't allowed in HTML 4.
Though this restriction has been lifted in HTML 5, an ID should start
with a letter for compatibility."
It's better to avoid them, if possible and use just alpha-numeric values for ids.
<script src="https://code.jquery.com/jquery-3.1.0.js"></script>
<input type=text id="x" value=0>
<script>console.log($('#x').val())</script>

Keep an element by id in a html string using javascript or jquery

I have a html string that contains:
<div class="infodiv">
<p id="111"><span class="text">111</span></p>
<p id="222"><span class="text">222</span></p>
<p id="333"><span class="text">333</span></p>
</div>
I will put it on the infowindow content on Google Maps.
However, I want to remove some elements by id before showing on the infowindow.
For example: I want to keep only an element with id=111.
So, my html string will only show:
<div class="infodiv">
<p id="111"><span class="text">111</span></p>
</div>
Any ideas how can I achieve it?
Thanks
If you only want to keep a single child of .infodiv, :not is a good choice. Otherwise, take a look at the filter() method.
Can you use the :not css selector in jQuery after using jQuery.parseHTML()?
$(".infodiv p:not(#111)").remove();
console.log($(".infodiv").html())
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="infodiv">
<p id="111"><span class="text">111</span><span></span></p>
<p id="222"><span class="text">222</span><span></span></p>
<p id="333"><span class="text">333</span><span></span></p>
</div>
Try This:-
$('.infodiv p:not(#111)').remove();
An id of an HTML element cannot begin with digits [0-9]
6 Basic HTML data types
ID and NAME tokens must begin with a letter ([A-Za-z]) and may be
followed by any number of letters, digits ([0-9]), hyphens ("-"),
underscores ("_"), colons (":"), and periods (".").
Substitute the first digit for a letter, for example "a" at id attribute at HTML.
To convert the HTML string to DOM elements you can set the HTML at .innerHTML of <template> element.
Create an array of last portion of id's that should be removed from HTML string, iterate .children of parent element, call .removeChild() with .querySelector() and attribute ends with selector, use .replace() to remove unnecessary newline characters from resulting HTML string.
const html = `<div class="infodiv">
<p id="111"><span class="text">111</span></p>
<p id="222"><span class="text">222</span></p>
<p id="333"><span class="text">333</span></p>
</div>`;
const template = document.createElement("template");
template.innerHTML = html;
const p = template.content.children[0];
const not = ["222", "333"];
for (let id of not) {
p.removeChild(p.querySelector(`[id="${id}"]`))
}
let parsedHTML = template.innerHTML.replace(/\n/g, "");
console.log(parsedHTML);

Attribute data_nonce, data_action, data_postid not allowed errors

I am checking code on w3c validator and I keep getting these errors for each individual blog and portfolio post that has the "Like" button attached to it. Is there something I can do to correct these errors so they validate properly?
Here is a sample of the code:
<a href="#" class="like " title="Like this" data_action="likepost" data_postid="74" data_nonce="13e20f93ee">
<span class="glyphicon glyphicon-heart"></span>
<span class="likecount">2</span>
</a>
Make sure you have doctype declaration like:
<!DOCTYPE html>
and replace the custom attributes as :
data-action data-postid and so on.
Note the hyphen instead of underscore. HTML5 allows custom attributes and suggests to use those which starts with data- .
A custom data attribute is an attribute in no namespace whose name starts with the string data-, has at least one character after the hyphen, is XML-compatible, and contains no uppercase ASCII letters
Reference

document.getElementById not working for <a> tag

I'm very new to js so kindly help me with this.
I am trying to add a class to a tag using onClick.
The code is as shown below:
<a class="gkvSprite" href="#" id="abc" onClick="showhide('1')">Click 1</a>
<a class="gkvSprite" href="#" id="def" onClick="showhide('2')">Click 2</a>
<a class="gkvSprite" href="#" id="hij" onClick="showhide('3')">Click 3</a>
Now when i click i need to add a class called "selected" for the one i select.
I tried using setAttribute and add class of jquery as well but was not successful
When i alert the document.getelementbyId(123) it gives out the link.
Can someone kindly help me?
Thanks in Advance
Alloi
id should begin with an alphabet.
Official specification
ID and NAME tokens must begin with a letter ([A-Za-z]) and may be followed by any number of letters, digits ([0-9]), hyphens ("-"), underscores ("_"), colons (":"), and periods (".").
Also,
var element = document.getElementById('id');
element.className += "newClass";
The showhide() should do something like above.
Without seeing the code for showhide there is no way to see exactly what you're doing wrong. Since you mention jQuery, here is how to do what you describe with it:
$('.gkvSprite').click(function() {
$(this).addClass('selected');
});
It's also worth noting that it's invalid to start an ID with a number.

need help with jquery selector

I have a following HTML :
<ul class="someclass">
<li id="1">
<button type="button" class="grey"></button>
</li>
<li id="2">
<button type="button" class="grey"></button>
</li>
<li id="44">
<button type="button" class="grey"></button>
</li>
<li id="54">
<button type="button" class="grey"></button>
</li>
</ul>
Now here is what I'm trying to accomplish with jquery :
When button is clicked to find out id of parent li, here is how I tried and failed:
$(".grey").live('click', function(){
alert($(this).parents("li").attr("id"));
alert($(this).parents("li:first").attr("id"));
});
Both give me null alerted, how can I do this ?
QUESTION UPDATE
Ah yes, I forgot to mention that this button element is not exactly in the li tag, its created on-the-fly when li is hovered, using append? I wrote this example just so you could get Idea what I'm trying
ANOTHER UPDATE :
When I try just $(this).closest("li"); I get [object Object] alerted but if I add attr("id"); I get null
I think it might be an issue with your id values: you're not allowed to use tokens which start with a number. IIRC, Firefox won't mind, but IE fails on it (as it should). Change the ids to have a prefix, eg: "item_44" and it should be ok.
Source: http://www.w3.org/TR/html4/types.html
ID and NAME tokens must begin with a letter ([A-Za-z]) and may be followed by any number of letters, digits ([0-9]), hyphens ("-"), underscores ("_"), colons (":"), and periods (".").
It works for me. EDIT: But not in Internet Explorer. As others have mentioned, IDs cannot start with a number. You should probably use a different attribute instead.
The best way do do this is to call the closest method:
$(this).closest('li')
It looks fine to me, though, since you're only traveling one level up, you only need .parent(), not .parents() ... but best might be .closest() (you can read up on it here).

Categories