Set data attribute based on text of element? - javascript

Is it possible to set the value of a data-* attribute based on the text of the HTML element? Schematically, this is what I have in mind:
<div data-text={this.text}>example</div>
resulting in data-text="example".
I think it may be possible if you set an id and then get the element by that, like this:
<div id="exampleId" data-text={document.getElementById("exampleId").textContent}>example</div>
But this is not what I'm hoping for because it requires setting an id ahead of time (so may as well just set the data attribute ahead of time). What I'm aiming for avoids the need to set anything specific to the element ahead of time and uses a property of the element itself to set that.
Maybe this isn't even a well defined question! But figured I'd ask. Thanks in advance :)

You could use querySelectorAll and apply logic to each element that has a data-text attribute like this:
const elements = document.querySelectorAll("[data-text]")
elements.forEach(element => {
element.setAttribute("data-text", element.innerText)
})

Related

Using placeholder as the typical id attribute in JavaScript

This question will probably either be extremely someone or flat out impossible. Inside of JavaScript how would I go about changing the value attribute of a input tag in html based on the placeholder value?
This question does sound dumb as a normal person would just set each of the divisions with different ids and change it that way. However, I’m creating an extension for a page with JavaScript that doesn’t have id values on the input tags.
Note: all of the placeholder texts are different, there are pretty much no id parent divisions except the wrapper, all the classes are the same for the input tag I wish to modify.
Thanks in advance. (It’s a dumb question I know. Forgive me)
Html I’m editing
<input type=“tel” maxlength=“1” placeholder=“1” value class=“UIInput-input>
It’s the same thing for the rest but each time the place holder goes up by one.
To find elements in the DOM based on attributes other than ID or Class, you can use the document.querySelector() method.
In your particular example, you would use it like this:
var newValue = 'my new value for my input element';
document.querySelector('input[placeholder="1"]').value = newValue;

multiple elements with ng-if and always only 1 of them is shown, can they share the same id?

As in title. I want to have 2 elements with ng-if and the same id, only 1 of them is shown at the same time. I am wondering if they can have the same id, since ng-if will remove 1 of the elements, so there will be only 1 element with that id.
I mean not only if it can be done, but also if it's a good way of doing things.
Here is the code sample of what I have in mind (it's been simplified):
<span id="elementType" ng-if="vm.type === 1">type1</span>
<span id="elementType" ng-if="vm.type === 2">type2</span>
Let's say that vm.type can only have values of 1 and 2.
Edit: Using a class instead of id is not possible for me. I am just wondering if I can use a single id for every element, or do all of them need to have separate id.
Edit2: I cannot use a class and need ids because I make these changes for tests, which rely on testing by ids. I cannot change that, so using class is not an option for me and is not an answer to my question at all.
Edit3: I am also absolutely sure that there will always be only one of the elements with ng-if displayed. I only need it for displaying element type, and there will always be exactly one type. If by any chance, the requirements change, it would already require massive changes, compared to which, changing things like displaying of the element type is not a problem at all.
You can see my fiddle that is based on your code.
Setting same 'id' on different element
$scope.changeType = function (){
if($scope.type===1){
$scope.type = 2;
} else if($scope.type===2){
$scope.type = 1;
}
};
This is handled by using 'ng-click', so it might be able to far from perfect for your purpose.
And if you use 'ng-if', you can set same 'ID' on different elements.
But using same id is not good because anybody doesn't know when errors occur from that.
And welcome every feedback. :)
To answer your question, Yes.
In the setup you outlined, it's ok since only one element is present in the DOM at a time.
I ran into the same situation, due to existing restrictions. After looking at the id attribute according to W3, as long as there is only one element with the ID in the DOM tree, it should be ok. ng-if removes the element from the DOM so it should be acceptable.
NOTE: Some of the folks in the comments made some very good point. It is generally bad practice to have multiple elements with the same ID, as noted in the comments. Read comments for more info and to get the context.

add attribute to DOM element

I have a modal form that is generated using bootstrap 3. It doesn't look like there is a reliable way to determine when that form is being shown onscreen. I am attempting to create one. I attached two events to my DOM element that signal when it is shown and when it is hidden.
jq_modal_login_form = $('#modal-login-form')[0]
jq_modal_login_form.on('shown.bs.modal', function () {
jq_modal_login_form.active_onscreen = true;
});
jq_modal_login_form.on('hidden.bs.modal', function () {
jq_modal_login_form.active_onscreen = false;
});
I tried to give an attribute named active_onscreen to the DOM element above. When I look at the DOM element in the debugger later, the attribute is not present.
I should mention that I am VERY new to javascript. Is attribute even the right word to use here? It looks like attribute is a bit of a misnomer as well. It could be an attribute of the object but could also be an attribute of the object.attributes attribute, right? I assume the later is where styling ect., goes and is not what I want to change. Does anyone have some insight as to what I should be doing here?
In jQuery:
$('selector').attr('attribute_name', 'value');
However, you can should only use predefined attributes as creating custom attributes requires additional setup (see this question) that is not necessary in your case.
In your case, you may just want to add a active_onscreen class to the element. Classes are meant to be used to identify elements (and not just for CSS), so they are perfect for this applicaiton. You would use this to add a class to an element:
$('selector').addClass('active_onscreen').
When it is no longer active, you would use this to remove the class:
$('selector').removeClass('active_onscreen').
What you are doing here is adding a property of the DOM object - not an attribute of the element.
Adding an attribute does not necessarily make the property mirror it. Only built-in properties do this.
If you want to set an attribute, but not the property, you can use jQuery's .attr() method.
If you just want to see if a given modal is open, Bootstrap does that for you. You can check the bs.modal data attribute:
$("element").data('bs.modal').isShown;
or a class (but this method is prone to race conditions):
$('#myModal').hasClass('in');

Setting an attribute to the last position

Is it possible to set a new attribute to the last position of a html element using javascript/jQuery?
This would be helpfull for me in a case where the attribute order is important to decide whether the paragraph has changed or not.
Example:
<p attribute1="true" attribute2="true">
Now, i would like to add a third attribute so that the resulting paragraph would look like
<p attribute1="true" attribute2="true" attribute3="true">
No, it's not possible. Attributes are unordered in HTML and XHTML markup languages, so browsers are free to return them in whatever order they like, e.g. alphabetic, specified, etc.
You should rethink your approach, for instance using the .data() method to track changes:
$("#el").data("changeHistory", []);
// ...
$("#el").data("changeHistory").push(new Date().toString());
Optimally you should never be in a position where you need to read attributes in order (by index).
If you have an element like so <div id="container">, you can add an attribute using jQuery like so $('#container').attr('disabled', true);. Keep in mind this should add the attribute to the end of the element.
Another tip is if you are looking to modify a DOM element attribute such as style, consider looking at the jQuery API to see what methods are avialable before writing anything too crude. For example, if you wanted to add a style you could simply do $('#container').addClass('hover');

Stick ID to the HTML element (using js) instead of id-attribute?

First post on stackoverflow. Hope everything is right!
I'm thinking of attaching an ID value to the HTML element itself via JavaScript, instead of using the HTML id attribute.
For instance, say that JavaScript variable htmlElement is a div. So htmlElement.cssName would tell us its CSS class.
Now, how about doing
htmlElement.idProperty = "someValue"
in JavaScript instead of doing <div id="someValue">? Then I can use the idProperty in say event handlers.
this.idProperty
That simple!
Is there something wrong in doing so?
EDIT: Thanks for yor answers! Very helpful and instructive. I wish I could check green on all of them!
no, you can do it the way you like it, if you are dynamically creating this item you should use this method, if you are doing this inside html I recommend you to just put the name of the id in html too.
However a small note. Use element.id instead of idProperty.
element.id = 'my-id';
You can use the createAttribute method to add an id to the element like this:
id = document.createAttribute('id');
id.value = "someValue";
htmlElement.setAttributeNode(id);
What you're doing there is adding a runtime property (in your case, called idProperty) to an HTMLElement object instance. You can get away with doing that in your JavaScript code (the Prototype library does it all the time). Makes me uncomfortable, but it does work on all major browsers.
If you want to be able to specify these in HTML markup as well, though, I'd use attributes instead. You can create attributes with any names you want, although to be careful I'd use names like data-xyz (e.g., use a data- prefix) as that's the HTML5 standard way of using your own attributes. Then you use getAttribute to get the value and setAttribute to set/update the value.

Categories

Resources