custom attr selector using jquery - javascript

<div id="placeholdSlots">
<div sort-helper="1"></div>
</div>
How select the div using sort-helper custom attr? I know attr('sort-helper') can only get the value.

$('div[sort-helper]');
or in vanillaJS
document.querySelectorAll('div[sort-helper]');
Anyway I would suggest to use a data-* attribute instead, e.g.
<div data-sort-helper="1"></div>

use jQuery attribute selector
alert($('div[sort-helper="1"]').html());
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div id="placeholdSlots">
<div sort-helper="1">abc</div>
</div>

jQuery is not the only way. You can use direct Javascript, like this:
Retrieving the firt div with an attribute called sort-helper
var elem = document.querySelector("[sort-helper]");
Retrieving all divs with an attribute called sort-helper
var list = document.querySelectorAll("[sort-helper]");
This is faster that jQuery because it is native code. And it is now cross-browser (for modern browsers ;-)).

Related

How to select all the HTML elements having a custom attribute?

I know I can select all the HTML elements with a custom attribute by just doing:
$('p[mytag]')
As you can see, I also need to specify the actual HTML div type (a p element in this case). But what if I need to retrieve all the HTML elements irrespective of their type?
Consider this code:
<p>11111111111111</p>
<p mytag="nina">2222222222</p>
<div>33333333333</div>
<div mytag="sara">4444444444</div>
how I can select the 2 html elements (the p and the div) with custom attribute mytag?
You just need to use $("[mytag]")
console.log($("[mytag]"))
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<p>11111111111111</p>
<p mytag="nina">2222222222</p>
<div>33333333333</div>
<div mytag="sara">4444444444</div>
Use querySelectorAll (javascript) :
document.querySelectorAll('[mytag]');
Or even simpler with jQuery:
$('[mytag]');

dynamically changing custom html values using jquery

<div data-react-class="Duration" data-react-props="{"startDate":"","endDate":""}">
I have this in my html. How can I change the startDate and endDate values in data-react-props using jquery?
add an ID to the div:
<div id="sample" data-react-class="Duration" data-react-props="{"startDate":"","endDate":""}">
And use the setAttribute method:
document.getElementsByID('sample').setAttribute('data-react-props', '{"startDate":"","endDate":""}');
You can use jQuery data selectors
$("div[data-react-class='duration']").attr("data-react-props","{'startDate':'12-12-2017', 'endDate':'01-01-2018'}");

Storing object ID in HTML document: id vs data-id vs?

I would like to have an opinion on storing RESTful object IDs in document for accessing it later from JavaScript.
Theoretically speaking using id for addressing elements in HTML doesn't cut it anymore. Same element can be repeated twice on the page say in "Recent" and "Most Popular" queries which breaks the main point of using id.
HAML even has this nice syntax sugar:
%div[object]
becomes:
<div class="object" id="object_1">
But like I said, seems that it is not a good approach. So I am wondering what is the best way to store objects id in DOM?
Is this the current proper approach?
<div data-id="object_1">
An ID is intended to uniquely identify an element, so if you have a case where you want to identify two or more elements by some common identifier, you can use ID but it may not be the best option in your case.
You can use IDs like:
<div id="d0">Original Div</div>
<div id="d0-0">Copy of original div</div>
<div id="d1">Another original Div</div>
<div id="d1-0">Another copy of original div</div>
<div id="d1-1">Another copy of original div</div>
and get all the d1 elements using:
document.querySelectorAll('[id^=d1]');
or just d1 divs:
document.querySelectorAll('div[id^=d1]')
You could also use a class:
<div id="d0" class="d0">Original Div</div>
<div id="..." class="d0">Copy of original div</div>
<div id="d1" class="d1">Another original Div</div>
<div id="..." class="d1">Another copy of original div</div>
<div id="..." class="d1">Another copy of original div</div>
and:
document.querySelectorAll('.d1')
Or use data- attributes the same way. Whatever suits.
You can also have a kind of MVC architecture where an object stores element relationships through references based on ID or whatever. Just think outside the box a bit.
The purpose why data-selectors where introduces is because the users neednt want to use class or anyother attributes to store value.Kindly use data-selectors itself. In order to make it easy to access them use attributes selector i.e. [attribute='value']. PFB the fiddle for the same and also the example
jsfiddle
<!DOCTYPE html>
<html>
<head>
<script src="//code.jquery.com/jquery-git2.js"></script>
<meta charset="utf-8">
<title>JS Bin</title>
</head>
<body onload="call()">
<div id="1" data-check='1'></div>
<div id="2" data-check='1'>sdf</div>
<div data-check='1'>sdf</div>
<div data-check='1'>sdf</div>
<div data-check='1'>sdf</div>
</body>
</html>
function call()
{
$("#1").html($('[data-check="1"]').length);
$("#2").html( document.querySelectorAll('[data-check="1"]').length);
}
Output: 5 5 sdf sdf sdf
#RobG is right by using 'class' you can get array of elements in JavaScript as-
var divs=document.getElelementsByClassName("className");
\\And you can loop through it(`divs[i]`).
AND according to #RobG and #Barmar data-* attribute is also a good option.
But here is some point(just point, not negative or positive, its totally depends on your application need) I want to discuss:
1] data-* element is HTML5's new attribute. Documentation
2] To retrieve elements in javascript, You need to use jQuery or more bit of JavaScript, coz all direct function available have specific browser support:
Like document.querySelector("CSS selector"); IE8+
document.getElementsByClassName("className"). IE9+
document.querySelectorAll("CSS selector"); etc.
So, basically for this point you need to choose according to your app need and browser compatibility.
3] Performance issue is also there on selecting by data-* attribute... Source
But, generally and if we go for latest application and selecting HTML5, data-* attribute + jQuery is a good option.
I was wondering about this too. Here's my POV using an example component.
CSS - styling across all buttons
Elements should not be referenced in JS using CSS classes because if you have multiple buttons that need to function differently, adding unique CSS classes for each component will get messy.
<div class="my-component">
JS - Grab the component when it can only appear once on a page
While browsers may handle multiple id okay, it would harm maintenance since this would be unexpected behavior from an id.
<div id="my-component">
const myComponent = document.querySelector('#my-component')
JS - Grab the component when it can appear multiple times on a page
ref or data-id could both work. ref has been popularized by React and Vue, so it may be more familiar to developers.
<div ref="my-component">
const myComponents = document.querySelectorAll('[ref="my-component"]')
or
<div data-id="my-component">
const myComponents = document.querySelectorAll('[data-id="my-component"]')

Custom attributes

I would like to get the value of custom attributes. For exemple, for this:
<div style="-my-data:3;" id="foo" ></div>
I would like to write something like that:
document.getElementById("foo").style.myData;
But it's not working. How can I do?
You should be using HTML5's custom data-* attributes instead:
<div data-myDataName="3" id="foo"></div>
Then, to get it via JavaScript, just use this:
document.getElementById('foo').getAttribute('data-myDataName'); // '3'
Here's the fiddle: http://jsfiddle.net/c55nf/
P.S. Even though it's part of HTML5, it'll still work in older browsers. It was just standardized in HTML5.
use the html data attribute:
<div data-style="3" id="foo"></div>
and then use
document.getElementById("foo").getAttribute("data-style");
to retrieve the information
Use HTML custom data attributes:
HTML:
<div data-myval="3" id="foo" ></div>​
JavaScript
alert(document.getElementById("foo").getAttribute('data-myval'));​
See the fiddle.

How to select an object in JQuery?

I'm beginner in JQuery, how could I select an object using JQuery ?
This is the code:
<script type="text/javascript" language="javascript">
function Hide(senderID) {
$("#" + senderID).hide(200);
// this exception is thrown // Microsoft JScript runtime error: Object expected
}
</script>
<div id="div1" onclick="javascript:Hide(this.id)"
Any help!
Don't:
get an id from an element
pass that id to a function
use the id to get the element.
Do: Just pass the element.
Don't stick javascript: at the front of an intrinsic event attribute, it doesn't mean what you think it means.
Don't use intrinsic event attributes for that matter (although I didn't fix this in this example). Use unobtrusive JS.
Avoid triggering events based on clicks on a div. This can't be targeted with a focus based navigation device (such as using the tab key on the keyboard and numerous devices used by people with disabilities) without using new features introduced in HTML 5 that don't see widespread support yet. Use an element that is designed as an interaction control (such as a button). (Also not fixed in the example below)
Example:
function Hide(sender) {
$(sender).hide(200);
}
<div id="div1" onclick="Hide(this)"
Code is exactly the same as yours, I added the correct tags, and the call to include the jquery library:
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.4/jquery.min.js"></script>
<script>
function Hide(senderID) {
$("#" + senderID).hide();
}
</script>
<div id="div1" onclick="javascript:Hide(this.id)">Click Me</div>
function Hide(sender) {
$(sender).hide(200);
}
<div id="div1" onclick="javascript:Hide(this)"></div>
hope it helps
I can't resist. Why not use jQuery's full power?
HTML:
<div class="hideable-div">Click me and get rid of me.</div>
jQuery:
$('.hideable-div').click(function () {
$(this).hide(200);
});
you misplaced those "" in
<div id="div1" class=""hideable-div>Click me and get rid of me.</div>
Should be like
<div id="div1" class="hideable-div">Click me and get rid of me.</div>

Categories