Not Able to Select a Class With Parent Specification in Vanilla JavaScript - javascript

Can you please let me know how can I get this done in vanilla JavaScript? I am able to select the .pay-plan-price text which it's parent has active class like this in jQuery
var fee = $('.plan-box.active .pay-plan-price').text();
But I need to do same select in core js format. I tried this
var fee = document.getElementsByClassName('.plan-box.active .pay-plan-price');
console.log(fee)
but in return I am getting HTNLCollection instead of the text of .pay-plan-price which has parent .plan-box.active

You can use document.querySelector to select an element using a similar selector as jquery accepts:
document.querySelector('.plan-box.active .pay-plan-price');
And then of course you need to get a text from that element, so use also textContent or innerText property on the returned element.
Example:
var fee = document.querySelector('.plan-box.active .pay-plan-price').textContent;
console.log(fee);

Related

select a string after a substring in an element's class name

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);

Select all the elements within an element having an attribute set to a specific value

I have the followings defined :
var excludedFiltersPanel = $("#excludedFiltersPanel");
var includedfiltersPanel = $("#includedfiltersPanel");
where *Panel is just a div.
in excludedFiltersPanel there are some div's with attribute data-iscorefilter="true" e.g. :
<div id="filterPanel-LastName" class="filterPanel" data-iscorefilter="true">
<Some Stuff here!>
</div>
I am trying to get them and move them to includedfiltersPanel:
It seems neither of these is a correct syntax:
excludedFiltersPanel.('[data-iscorefilter="true"]')
excludedFiltersPanel.$('[data-iscorefilter="true"]')
1.What is the correct syntax?
2.How do I append them to includedfiltersPanel? (I know how to append a single item, but not sure what is the common good practice here, e.g. using for loop or some JQuery magic)
Since excludedFiltersPanel there are some div's with attribute data-iscorefilter="true"
Use .find()
Description: Get the descendants of each element in the current set of matched elements, filtered by a selector, jQuery object, or element.
It would look like :
excludedFiltersPanel.find('[data-iscorefilter="true"]')

How to get the value of inner attribute of an li using jquery?

I have following code in Java script from which i have to need get the value on an inner attribute of <li>.
<li class="selected" data-val="1">
I have get the tag using
var a = document.getElementsByClassName('selected');
it is providing me <li> whole tag that is fine. But i have to need get the value of data-val attribute (which is within the <li>) that is 1.
How can i get the value of data-val using variable a that is defined.
Please explain..
Here a is a collection object so you need to get the element reference using index then use .getAttribute() to get the attribute value()
var a = document.getElementsByClassName('selected');
var val = a? a[0].getAttribute('data-val') : '';
//another option for modern browsers
// val = a[0].dataset.val
Since you have jQuery, you can use jQuery to select the element and then use data api like
var val = $('.selected').data('val')
With jQuery you can use $(a).attr("data-val").
Without jQuery you can use a.getAttribute("data-val")
Try this approach
var dataValValue = $(".selected").attr("data-val");
It will get data-val attribute from first li from all li with class .selected
There are two ways, using jQuery and the first returned element in a:
$.data(a[0],"val");
$(a[0]).data("val");
Both are equivalent. Sorry, they're not equivalent, since the first one is lower level, and does not process data-* attributes by itself.
There's no need to use .attr() since data-* attributes are processed automatically in the case of the second one.

Storing data in html dynamically (html5)

I am creating a dynamic div in html which consists of multiple checkboxes. All these checkboxes and divs are being dynamically added to the html. I need to store some data about each div in the html to be accessed by javascript later. Can anyone show me an example where data can be added and retrieved dynamically in a div? I know HTML5 allows it and there are some other hacks to do it, but I am having trouble with syntax I guess.
Try to do it using JavaScript:
SomeClass.someVariable = document.getElementById('divid');
Otherwise if you mean to access custom data that has to used as attribute in your HTML tags then use
data-XXX = 'YYY';
And access it with JS:
document.getElementById('divid').dataset.XXX;
This post explains data-* attributes.
You can create custom attributes within your divs like this:
<div id="div1" data-text="Hello. This is a custom attribute."></div>
Notice the data- prefix. this is absolutely necessary.
Then (using jQuery) you can access the custom attribute:
$('#div1').data('text'); => "Hello. This is a custom attribute."
So using this you can do stuff like:
if($('#div1').data('text') != "FreddieBobman"){
alert("HI!");
} else {
alert("Forever Alone!");
}
The above example will alert "HI!" because $('#div1').data('text') does not contain
FreddieBobman, it is in fact "Hello. This is a custom attribute."
To create these attributes use the following:
$('#div1').attr('data-name', 'value');
Our div with id of div1 now has another attribute, data-name, and the attribute has a value of value. Of course, you can change the value of attributes as well:
<div id="div1" data-text="Hello. This is a custom attribute."></div>
<script src="jquery.js"></script>
<script>
(function(){
$('#div1').attr('data-text', 'This is cool.');
}());
</script>
Now the div has data-text equal to "This is cool.", not "Hello. This is a custom attribute."
It is Obtain by the data attributes that you add dynamically to the elements ,And retrieve when you want !
SET Attribute :
var div = document.createElement('div');
div.setAttribute('data','my_data');
div.innerHTML = "I am a div";
document.body.appendChild(div);
GET Attribute :
div.getAttribute('data')
WORKING DEMO
you can use attributes for your html tags. Also, in html5 you can also use custom attributes
What you want is to add or retrieve data from div tags dynamically?
Using javascript function you can simply get corresponding div element using its id,
var container = document.getElementById('your_element_id');
Then you can add what you want.
var stringToAdd = "<p>something you want to add</p>";
container.innerHTML = stringToAdd;
Also you can use a different class with different features and set it as your div class.
you need to add your features inside style tag under your class name. Then,
var elementID = document.getElementById(ID);
elementID.className ="your_new_class_name";
or you can set attributes for your tag.
elementID.setAttribute('display','inline');
Using jquery with javascript,
var elementID = document.getElementById(ID);
$(elementID).replaceWith( "<p>something you want to replace</p>" );
using class name or id you can dynamically append content using,
var stringToAdd = "<p>something you want to add</p>";
$(".your_class_name").append(stringToAdd);
also you can remove whole element using,
$(elementID).remove();

How to get attributes of container in jquery?

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');

Categories