I am trying to take the value of a select element and match it to a dataset of another element to affect a transition on that element.
So I have two tags with data in them:
<select data-name="name goes here" updateElement()></select>
<select value="what ever option is picked" applyTransition()></select>
When ever you change the option of data-name it will update a variable that holds the element I am trying to apply the transition affect on.
The goal is when you change the select with the data-name it updates and element the other select applies a transition too.
I haven't shared any of the actual code because it is a lot and would like to just share what is needed.
Okay so I figured this out after banging my head against the console.
const yourElements = document.querySelectorAll(".your-class-name");
let selectedElement;
So if your elements have a data-property set you can "pluck" that one out.
for(let i = 0; i < yourElements.length; i++){
if(select.value === your-class-name[i].dataset.property){
selectedElement = document.querySelector(`[data-property=
${locationHands[i].dataset.property}]`);}
Then you should be able to see selectedElement as the element you want.
You can then use that variable where ever.
If you know of a better or more efficient way to achieve this, please let me know.
Related
I want to know if it is possible to go to a site and retrieve the text of an element
i think something like
a = page("www.site.com")
b = a.getElementByClass("name")
console.log(b.text)
this is possible?
Yes. It's called the innerText property. See https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement/innerText
That depends,
If you want to get the innerText of the elements, then
let elements = document.getElementsByClassName("YourClassName");
for(let i=0;i<elements.length; i++){
/*doSOmething*/
console.log(elements[i].innerText);
}
Many elements may have same className. So, if you want to access some specific Element, then you should either know the index of the element or you need to use id for the element.
let element = document.getElementById("YourElementId");
/*doSOmething*/
console.log(element.innerText);
I have an element that contains an input text, to get the input text I'm using the jQuery method find.
The input text has a class name like this page-id-x with the x is variable, so I want to select that number after the substring page-id, and this is what I tried :
var id = ui.item.find('input').attr('class').split(/\s+/).filter(function(s){
return s.includes('page-id-');
})[0].split('-')[2];
console.log(id);
I think this code is too complicated, but I couldn't figure out some other way to do it.
If someone knows a better way, I'll be thankful.
Thanks in advance.
I'm going to assume the x part of page-id-x, not the id part, is what varies (since that's what your code assumes).
Another way to do it is with a regular expression, but I'm not sure I'd call it simpler:
var id = ui.item
.find('input')
.attr('class')
.match(/(?:^|\s)page-id-([^- ]+)(?:\s|$)/)[1];
Example:
var ui = {
item: $("#item")
};
var id = ui.item
.find('input')
.attr("class")
.match(/(?:^|\s)page-id-([^- ]+)(?:\s|$)/)[1];
console.log(id);
<div id="item">
<input class="foo page-id-23 bar">
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
The above makes the same assumptions your current code does, which are:
The first input in ui.item is the one you want
It will have the relevant class name
I assume those are okay, as your question is asking for an alternative, suggesting what you have is working.
As you're using jQuery, take a look at this: https://api.jquery.com/category/selectors/attribute-selectors/
For your case, you can use $('[class^="page-id-"'). These types of selectors (listed on the link above) actually work in CSS, too. (At least most should, if not all.)
To get the number after page-id-, my suggestion would be to store that number in some other HTML attribute, like data-pageID="1" or the like.
So you could have:
<div id="page-id-3" data-pageID="3">CONTENT</div>
Then, when you have the DOM element using $('[class^="page-id-"'), you can access that number with .attr('data-pageID').val().
If you can control the HTML markup, instead of using class names, you can use data attributes instead. For example, instead of:
<input class="page-id-1">
You can use:
<input data-page-id="1">
Then jQuery can find this element effortlessly:
$('[data-page-id]').attr('data-page-id')
You can find your element using the *= selector.
let elem = document.querySelector('[class*=page-id-]')
Once you have the element, you can parse the id out:
let [base, id] = elem.className.match(/page-id-(\d+)/)
console.log('page id: %s', id);
I currently have about a dozen html buttons on a page, all with a unique value attribute assigned to them.
Firstly, I want to be able to get the values of these buttons and assign them into an array. Here is my code:
var myArray = [];
$("#buttonID").each(function(){
myArray.push($(this).attr("value"));
});
This works, however only takes the value from the first button, and then ignores the rest, despite them all have the same ID. Have I done something wrong with my .each() ?
Once I have solved that, I would like to then modify the above to only add values of those buttons with ".active" classes on them. i.e a user has selected them.
Your selector represents an ID hence the #this why it picks only one because ID's are supposed to be unique, you need to pick them by class name like .className after assigning this class name to all of your buttons
have a loonk at this http://www.w3schools.com/jquery/jquery_ref_selectors.asp
Let's say you decided to use a common class for your buttons instead of an ID. Example:
<button class="my-class".......
There's a wonderful jQuery method that would put the values of all the button's with this class in an array like so:
var myArray = $('.my-class').map(function() {
return this.value;
})
.get();
I have a 2 select boxes. The first select box alters the second. The second can have a small set of variable options.
What I have done is when the page loads I save the options as a variable.
var optionList = $('select[name="location"] option');
When the first select box changes. I then do something like below matching the value of the first select box to a switch statement then knocking out and adding new options to select box 2.
case 'add':
$('select[name="location"] option').remove();
$(optionList).each(function() {
$('select[name="location"]').append($(this));
});
$('select[name="location"] option:not(option[value="cart"])').remove();
break;
This all works fine.
What I need to do now is add an option to the optionList. I have tried both append and after. Append adds a new option inside the last option. After causes a jQuery error. Any idea how I do this?
var html = '<option value="'+v+'">'+l+'</label>';
$(optionList).append(html); // Fails
$(optionList).after(html); // jQuery error line 3
Firstly, you are appending an option tag, with a closing label tag, it should be:
var html = '<option value="'+v+'">'+l+'</option>';
Secondly, with the code you have it will append your new option after every existing option (as optionList is an array of all the existing option elements).
Instead you should just append it to the select element, like this:
$('select[name="location"]').append(html);
$('select[name="location"] option'); is selecting the options which are part of that select. So when you do $(optionList).append(html);, you are appending "html" to the each option in that results list.
Personally, I'd typically do something like:
var $mySelect = $('select[name="location"]');
var optionList = $mySelect.find('option');
...
$mySelect.append(html);
but you could also do something like this:
var optionList = $('select[name="location"] option');
...
optionList.filter(':first').parent().append(html);
The second option is less performant though.
optionList.push(html) didn't work because optionList is a jQuery-wrapped array of options (each one a jQuery-wrapped option), not a select's list of options within document.forms.
optionList.push($(html)) worked beause you wrapped the raw DOM element "html" with jQuery, and thus you were just adding another jQuery-wrapped option to optionList. You could save a character (and be a bit more jQueryish) if you instead did optionList.add($(html)). However, either of those would only add the "html" element to the optionList collection; it wouldn't actually add "html" to the DOM.
Last, two side notes... First, appending like you're doing in that loop is a really bad idea; you're hitting the DOM, and also triggering a repaint, on each time through the loop. You're far better creating an array of options, then doing something like
jQuery.fn.append.apply($('select[name="location"]'), objectArray);
That only does a single hit on the page, and triggers only one repaint. See http://www.learningjquery.com/2009/03/43439-reasons-to-use-append-correctly for more.
Second, $(optionList) is redundant and costs you some performance. optionList is already a jQuery object - ie, $('select[name="location"] option'). $(optionList) invokes the jQuery constructor, only to have it realize that optionList is already a jQuery object, and internally it is then converting your use of $(optionList) into jQuery actually just using optionList.
How can I get attributes values from an container using jquery ?
For example:
I have container div as:
<div id = "zone-2fPromotion-2f" class = "promotion">
here how can I get attribute id value using jquery and than how can I trim the value to get component information ?
update : how can i get attribute values ?
UPDATE: If I have multiple components on page with same div information than how would I know what attribute value is for which component ?
Thanks.
First, that seems to be a ridiculously long ID -- I'm sure it could be made much shorter while still retaining its uniqueness.
Anyway, on to the answer: First you need a way of accessing your "container" div. Typically, one might use a class or ID to get an element. For example, you could "select" this div with the following call to jQuery:
var container = jQuery('#zone-3a...'); // Fill in ... with really long ID
But, since you're asking how to retrieve the ID, I'm presuming that selecting it via the ID is not an option. You could also select it using the class, although it's not guarenteed to be the only element on the page with that class:
var container = jQuery('.promotion');
There are other ways to narrow down the search, such as:
jQuery('div.promotion');
jQuery('div.promotion:first');
Once you have a reference to your "container", you can retrieve the ID like so:
container.attr('id'); // => zone-3a...
// or:
container[0].id; // => zone-3a...
So assuming your div looks like this.
<div id="foo"/>
You could get the ID attribute by using the attr method.
$("div").attr("id);
That assumes that you only have one div on the page. Not really sure what component information you are looking to get?
You read node attributes with the attr() method.
var id = $( '.promotion' ).attr( 'id' );
In terms of parsing that ID for any other arbitrary information, I can't say since it looks like you're using some sort of proprietary format of which I have no knowledge.
loop thru and get all divs with the class promotion and get the id of each...
$('div.promotion').each(function(){
var attr = $(this).attr('id'); // or whatever attribute
});
or single
var myDivClass = $('zone-3a-2f-2f-2fPortal-2fPages-2fHome-2fZones-2fLeft-2f-7ccomponent-3a-2f-2f-2fSpm-2fComponents-2fPromotion-2f').attr('class');
or another single
var myDivID = $('.promotion').attr('id');