Access 'data-' attribute without jQuery - javascript

Can I access a data- attribute without jQuery?
It's easy with jQuery, but I can't see anywhere how to do it without jQuery.
If I search on Google 'without jQuery' all I get is jQuery examples.
Is it even possible?

On here I found this example:
<div id='strawberry-plant' data-fruit='12'></div>
<script>
// 'Getting' data-attributes using getAttribute
var plant = document.getElementById('strawberry-plant');
var fruitCount = plant.getAttribute('data-fruit'); // fruitCount = '12'
// 'Setting' data-attributes using setAttribute
plant.setAttribute('data-fruit', '7'); // Pesky birds
</script>
So it would appear very doable.
Update: Since Microsoft is now (2020) phasing out the old Internet Explorer engine in favour of a Chromium based Edge, the dataset property is likely to work everywhere. The exception will, for a time, be organizations and corporate networks where IE is still forced. At the time of writing this though - jsPerf still shows the get/setAttribute method as being faster than using dataset, at least on Chrome 81.

You could use the dataset attribute. As in:
element = document.getElementById("el");
alert(element.dataset.name); // element.dataset.name == data-name

It's just an attribute ... use getAttribute as with any other attribute : https://developer.mozilla.org/en/docs/DOM/element.getAttribute
Or am I missing the point of your question.

You can also use:
getAttribute('data-property');
Which is a bit cleaner and easier to read.
This will get the value of the data attribute.

I think you can try this:
var ele = document.getElementById("myelement");
if (ele.hasOwnProperty("data")) {
alert(ele.data);
}
OR use
alert(ele['data-property']);

Related

$('title').text() doesn't work in IE

I want to change the page title using jQuery, But it doesn't work in IE, Why?
The code like this:
alert( $('title').text() ); // empty in IE
$('title').text('Some Text!'); // Don't work in IE
Yes, we can use document.title = 'xxxx'; to change the title conent.
title.innerHTML is read-only in IE. Also looks like innerText has some limitations.
$(document).prop('title', 'Some Text!');
Here to answer your original question. It's a known bug.
alert($('title').text()); // empty in IE <= 8
The reason why this happens is because the page title is somewhat special in Internet Explorer <= 8; how special?
document.getElementsByTagName('title')[0].firstChild; // null
When you use jQuery.text() it iterates over all child nodes of an element and concatenates their text representations to form the final result; because the firstChild property is null, this will obviously not work.
The page title is available as innerText and innerHTML properties, but attempting to write those properties will cause an "unknown" runtime error.
if you want to use as much jQuery as you can,
$("title").innerHTML = $("title").attr("text", "New title");
works on IE8.
Using the document.title property is the simple cross-browser way to set or retrieve the document title. IE just doesn't want to play right
try this
document.title = "This is new title.";

How to get non-DOM properties of HTML in Javascript

Say a HTML snippet like this:
<div a_example = "x" b_example = "y" class = "z"></div>
What is the proper way to get the corresponding properties of a_example and b_example in Javascript?
Can xpath do the job?
Use getAttribute:
var elem = document.getElementsByClassName("z")[0],
a = elem.getAttribute("a_example");
Here's a working example.
But, as has already been mentioned, you should really be using HTML5 data-* attributes, otherwise your markup is invalid.
Some browsers will add all attributes as named properties of the DOM element, others will only add standard attributes. In both cases you can get non–standard attributes using getAttribute, however such a scheme is not recommended.
It is common to use standard attributes and DOM properties and only use getAttribute where necessary as it is inconsistently implemented in different browsers.
You should take a look at HTML5 data attributes, here is a useful article: http://html5doctor.com/html5-custom-data-attributes/
Reading data attributes from a tag is really easy, and a fallback is available for older browsers. An example from the article:
<div id="sunflower" data-leaves="47" data-plant-height="2.4m"></div>
<script>
// 'Getting' data-attributes using dataset
var plant = document.getElementById('sunflower');
var leaves = plant.dataset.leaves; // leaves = 47;
</script>
If you are using jQuery, it is as simple as saying:
HTML
<div id="testDiv" a_example = "x" b_example = "y" class = "z"></div>
Javascript:
var attr1 = $('#testDiv').attr('a_example');
element.getAttribute(attributename)
This should work for you.
I agree you should look at data attributes and better ways to do add non-standard attributes, but here's a 'raw' answer to your question, but I wouldn't treat this as universally supported (or advisable):
alert(document.getElementsByTagName('div')[0].getAttribute('b_example'));

Proper way to change text and elements on a page with JavaScript

I've been using innerHTML and innerText for a while to change elements and text on web pages and I've just discovered that they are not W3C standard.
I've now found that innerHTML can be replaced with createElement, setAttribute and a few others but what is the best method for changing text inside an element?
I found a textContent as well but is there a standard way and is it widly implemented across older browsers?
textContent isn't implemented in IE8 and lower. You can use createTextNode() similar to how you would use createElement(). However, I often use discovery techniques to find out which property I need to use and keep a reference to it:
// You can use a shorter variable name if you want
var innerTextOrTextContent = "textContent" in document.body
? "textContent" : "innerText";
// Set an element's text:
myElement[innerTextOrTextContent] = "Added using: "+innerTextOrTextContent;
The createTextNode() example:
var tNode = document.createTextNode("Added using createTextNode()");
myElement.appendChild(tNode);
Something I often forget about, you can also directly set a text node's value, if you can get a reference to it:
// childNodes[0] is a text node:
myElement.childNodes[0].nodeValue = "Added using nodeValue";
Example - http://jsfiddle.net/BxPaG/.
I think you can't go wrong by using whatever your javascript library offers for changing text (innerHtml for jQuery). After all one of the the main reasons for using such a library is having a platform that abstracts from different browser implementations.

why this javascript is line is Right and the other isn't

javascript with>
var customer=document.getElementById('custList').value;
and that works...
Why does it work BUT...
var customer=(form1.custList.value);
I get an error that form1 is not defined.
Especially why would this work in IE, and Chrome but not Firefox.
It seems just as clearly stated to me, but I am not a script engine
Just trying to understand
if you want to refer to a form object in your page, you may use the 'document.forms' object, that is an array of form objects in the document. suppose we have a form like this:
<form method="post" action="somthing.php" name="myContactForm" id="contact_form">
<input type="text" name="custList" id="custListId" />
</form>
to access the value in a correct way, you might use any of these methods:
first acccess the form, then the element.
var form = document.forms['myContactForm']; // use the 'name' attribute as the array key
// or if this is the first form appeared in the page. otherwise increase the index number to match the position of your target form.
var form = document.forms[0];
// or access the form directly
var form = document.getElementById('contact_form');
// now get the element, from the form. you can access form elements, by using their name attribute as the key in the elemetns array property of the form object.
var cust = form.elements['custList'].value();
or you can access a form element directly, without any form. you can refer any element in the document by its id, directly. no form is needed here.
var cust = document.getElementById('custListId');
all these statements are valid JavaScript that run on IE, firefox, opera, chrome, etc.
however you can refer to a form object in IE, by just calling its 'name' attribute. so this line works in IE (and as you are saying, chrome. I did not know that chrome handles it):
var cust = myContactForm.custList.value();
IE tries to map unknown window level properties (like myContactForm ) to elements by matching to their 'name' attribute.
I believe IE/Chrome/Opera incorrectly interpret id="form1" as name="form1" ( or vice versa? ) to account for legacy markup.
I would not rely on dom 0 level property accessing such as form1.custList and instead use document.getElementById. If it's too long to type, define a method to do it.. eg
function getId( id ) { return document.getElementById(id) }
Because the second idiom is not standard, while getElementById is, so it has to be supported by every browser to say that is javascript compatible.
Also, the second one should be, if I'm not mistaken, document.form1.custList.value.
Internet Explorer did a lot of things in it's own way. By all means, the first way is the correct way (using getElementById).
For backward compatibility many of these "bugs" still work, but you should not use them.
There are still differences between browsers. Using a JavaScript framework (like jQuery) helps a lot here, it is written to work well cross-browser (for the record, your code will be $('#custList').val(); using jQuery)
Internet Explorer stuffs all of your form elements by name into the window object as properties, which is fragile, incompatible, difficult to use with any finesse -- and what makes your second example work. Other browsers simply take the clean route of not implementing that interface at all, leaving you with the proper DOM functions. Or a toolkit. jQuery really is quite nice. ;)

How to add/update an attribute to an HTML element using JavaScript?

I'm trying to find a way that will add / update attribute using JavaScript. I know I can do it with setAttribute() function but that doesn't work in IE.
You can read here about the behaviour of attributes in many different browsers, including IE.
element.setAttribute() should do the trick, even in IE. Did you try it? If it doesn't work, then maybe
element.attributeName = 'value' might work.
What seems easy is actually tricky if you want to be completely compatible.
var e = document.createElement('div');
Let's say you have an id of 'div1' to add.
e['id'] = 'div1';
e.id = 'div1';
e.attributes['id'] = 'div1';
e.createAttribute('id','div1')
These will all work except the last in IE 5.5 (which is ancient history at this point but still is XP's default with no updates).
But there are contingencies, of course.
Will not work in IE prior to 8:e.attributes['style']
Will not error but won't actually set the class, it must be className:e['class'] .
However, if you're using attributes then this WILL work:e.attributes['class']
In summary, think of attributes as literal and object-oriented.
In literal, you just want it to spit out x='y' and not think about it. This is what attributes, setAttribute, createAttribute is for (except for IE's style exception). But because these are really objects things can get confused.
Since you are going to the trouble of properly creating a DOM element instead of jQuery innerHTML slop, I would treat it like one and stick with the e.className = 'fooClass' and e.id = 'fooID'. This is a design preference, but in this instance trying to treat is as anything other than an object works against you.
It will never backfire on you like the other methods might, just be aware of class being className and style being an object so it's style.width not style="width:50px". Also remember tagName but this is already set by createElement so you shouldn't need to worry about it.
This was longer than I wanted, but CSS manipulation in JS is tricky business.
Obligatory jQuery solution. Finds and sets the title attribute to foo. Note this selects a single element since I'm doing it by id, but you could easily set the same attribute on a collection by changing the selector.
$('#element').attr( 'title', 'foo' );
What do you want to do with the attribute? Is it an html attribute or something of your own?
Most of the time you can simply address it as a property: want to set a title on an element? element.title = "foo" will do it.
For your own custom JS attributes the DOM is naturally extensible (aka expando=true), the simple upshot of which is that you can do element.myCustomFlag = foo and subsequently read it without issue.

Categories

Resources