msDropDown Delete all options - javascript

Please let me know how can I remove/clear all options from msDropDown. I have tried the below code and its not working fine.
oHandler2 = $("#main").msDropDown().data("dd");
oHandler2.remove();
Thanks in Advance.
Lampy

You need to specify an index when calling the .remove() method and you can get the count of all options by accessing the childElementCount property. Then you just need to remove all the options. Example below:
var oHandler2 = $("#main").msDropDown().data("dd");
for(var i = 0; i < oHandler2.childElementCount; i++){
oHandler2.remove(0); //remove the current first option
}

In my opinion the best way to delete all item is
var oHandler = $("#main").msDropDown().data("dd");
oHandler.set("length", 0);

If you dont need to remove specify item, you can delete your element. And then create new one.
HTML
<div class="mainSection">
<div id="main"></div>
</div>
Script
<script>
$("#main").remove();
$(".mainSection").append("<div id='main'></div>");
$("#main").msDropDown().data("dd");
</script>

Related

How to loop through htmlcollection object?

I have looked at almost every question that has been asked here about htmlcollection.
So I have a div and I am fetching data and creating divs inside this div with ajax so they are not hardcoded.
this is how div look like before I fetch the data
<div id="tivvits"></div>
this is how div#tivvits looks like after I call function show_all_tivvits();
show_all_tivvits() is a function where I create a ajax request and create new divs
such as div#tivvit-21, div#tivvit-22, etc.
<div id="tivvits">
<div id="tivvit-19" class="grid-container">...</div>
<div id="tivvit-20" class="grid-container">...</div>
</div>
this is part of the js file
document.addEventListener("DOMContentLoaded", function(){
show_all_tivvits();
var t = document.getElementById('tivvits');
const j = t.getElementsByClassName("grid-container");
const k = Array.prototype.slice.call(j)
console.log(k);
for (var i = 0; i < k.length; i++) {
console.log(k[i]);
}
});
what I wanted to do in show_all_tivvits() function is I want to get the divs that are already in the div#tivvits and that way I am not gonna create them again but the problem is when I use console.log() to print out document.getElementById('tivvits').getElementsByClassName('grid-container') there are items in the htmlcollection but when I print out length it returns 0.
one more thing when I open inspect>source in chrome my index.php doesn't have updated div#tivvits.
I have tried almost every way to loop this htmlcollection but it is not working.
list of things I have tried;
Array.from(links)
Array.prototype.slice.call(links)
[].forEach.call(links, function (el) {...});
HTMLCollection.prototype[Symbol.iterator] = Array.prototype[Symbol.iterator];
HTMLCollection.prototype.forEach = Array.prototype.forEach;
It's not really clear, but are you looking for something like this?
targets = document.querySelectorAll('#tivvits > .grid-container')
for (let target of targets)
{console.log(target.id)}
This should select all <div> nodes which are direct children of the <div id="tivvits"> node and have a class attribute with the value "grid-container", and extract from them the attribute value of the id attribute.
Have a go with this
I use the spread operator to allow the use of map on the HTMLCollection
window.addEventListener("load", function() {
const gridContainers = document.querySelectorAll("#tivvits .grid-container");
const ids = [...gridContainers].map(div => div.id);
console.log(ids)
});
<div id="tivvits">
<div id="tivvit-19" class="grid-container">...</div>
<div id="tivvit-20" class="grid-container">...</div>
</div>
To just display change
const ids = [...gridContainers].map(div => div.id);
to
[...gridContainers].forEach(div => console.log(div.id));

javascript: how do i get the value of a specific attribute in a nested div

To simplify what I want to achieve, I want to get popular-laptop-deals from data-code="popular-laptop-deals" using a javascript bookmarklet alert.
<div class="display-table-column scroll-item display-block-xs top-padding-mini-xs tile-highlight category-tile" data-code="popular-laptop-deals" data-testid="tile-highlight">
These belong to a nested div where there are other <div> with data-code="". I'm trying to get the function to run through all and get all the other values from data-code="".
I have tried using the following script but it returns "undefined":
javascript:alert(document.getElementsByName("data-code")[0]);
Appreciate if someone could show or guide me on how i can achieve this.
Thanks in advance.
document.getElementsByName("data-code") is an empty NodeList because there are no elements with names, hence, no element with attribute data-code.
You can change getElementsByName to getElementsByTagName, etc. and then get its attribute value.
Also, data-* attributes can be accessed via the dataset property of an element, e.g. yourDiv.dataset.code.
alert(document.getElementsByTagName('div')[0].dataset.code);
<div class="display-table-column scroll-item display-block-xs top-padding-mini-xs tile-highlight category-tile" data-code="popular-laptop-deals" data-testid="tile-highlight">
With this, you can check all div tags on the page and add them to the array if contain data-code.
var divs = document.getElementsByTagName("div");
var result = [];
for (var i = 0; i < divs.length; i++) {
if (typeof divs[i].dataset.code !== "undefined") {
result.push(divs[i].dataset.code);
}
}
console.log(result)
With Jquery, you can achieve like as below.
Jquery:
alert($("div").attr("data-code"));
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="display-table-column scroll-item display-block-xs top-padding-mini-xs tile-highlight category-tile" data-code="popular-laptop-deals" data-testid="tile-highlight">
with querySelector select tag and with getAttribute select attribute
var attr_code = document.querySelector('div').getAttribute('data-code');
alert(attr_code);
<div class="display-table-column scroll-item display-block-xs top-padding-mini-xs tile-highlight category-tile" data-code="popular-laptop-deals" data-testid="tile-highlight">

i have many data-self element, but how can i get all of them?

just like this:
// with jquery i have tried
$('body').data('self'); // undefined
$('body').data('date-self'); //undefined
// but i can use this method to get the defined element
$('button').data('self'); // self
// with javascript
document.querySelector('button').dataset.self // self
<html>
<head>
</head>
<body>
<div data-self="self">self</div>
<span data-self="self">span self</div>
<ul>
<li data-self="self">li1 self</li>
<li data-self="self">li2 self</li>
</ul>
<button data-self="self">button self</button>
</body>
</html>
but i can't find a way to get all elements with 'data-self'.
if someone know, please tell me, any help would be greatly appreciated.
Well, first off, your HTML is invalid. date-self should probably be data-self, yes?
Second, getting the value in data-* attributes is done using the .data() method:
var dataSelf = $(".elem").data("self");
You can also get it directly from the attribute, like so:
var dataSelf = $(".elem").attr("data-self");
Selecting elements that have the data-self attribute is done as follows:
var elementsWithDataSelf = $("[data-self]");
You're just going to have to iterate over them all.
var $elems = $('[data-self]');
var selfs = [];
$elems.each(function ($elem) {
selfs.push($elem.data('self'));
});
You can get all elements where 'data-self' attribute is set using this query:
var elementList=document.querySelectorAll('[data-self]');
If you need to select all elements where 'data-self' attribute is equal to something then you can use next line:
var elementList=document.querySelectorAll('[data-self="something"]');

How to select from option menu in javascript

I need to be able to change certain option from select menu to be as default (start) value when I do something.
For example when I declare it, English language is default value.
How to change that with the code and not with the click.
<form id="form1" name="form1" method="post" action="">
<select name="websites1" id="websites1" style="width:120px" tabindex="1">
<option value="english" selected="selected" title="images/us.gif">English</option>
<option value="espanol" title="images/es.gif">Espanol</option>
<option value="italian" title="images/it.gif">Italiano</option>
</select>
</form>
In the body tag I have declared:
<script type="text/javascript">
$(document).ready(function() {
$("body select").msDropDown();
});
</script>
I am using this SCRIPT
I have tried all of the bellow examples and none this is good for me.
What else can I do change default select value.
This is working for me as mentioned in the docs:
$('#websites1').msDropDown().data('dd').set('selectedIndex',2);
This will select italian ;)
/edit:
Keep in mind that #Patrick M has a more advanced approach and he posted his approach before I posted mine ;)
If you are having weird css issues like I did, try this undocumented stuff:
$('#websites1_msa_2').click(); // this will also select the italian
As you can see the id is generated by $('#websites1_msa_2') the id of the selectbox plus the $('#websites1_msa_2') index of the option item.
A bit hacky but works ;)
So you could then define a JavaScript-Function like this:
var jQueryImageDD_selectByName = function(name) {
var children = $('#websites2_child').children();
for(var i=0;i<children.length;i++) {
var label = children[i].getElementsByTagName('span')[0].innerHTML;
if(label === name) {
children[i].click()
}
}
};
And then use it like this:
jQueryImageDD_selectByName('Italiano'); // will select Italiano :)
He does say
You can set almost all properties via object
So, just guessing from the documentation examples he provides on that page... I would think adapting this:
var oHandler = $('#comboboxid').msDropDown().data("dd");
oHandler.size([true|false]);
//Set or get the size property
To the .value property might work. So for you to set the language to Italian, try
var oHandler = $('#comboboxid').msDropDown().data("dd");
oHandler.value('italian');
// Or maybe the way to do it is this:
oHandler.set('value', 'italian');
// Or maybe 'value' shouldn't be in single quotes
//set property
If that doesn't work, you could try looping over all the properties, getting and comparing the value at each index and, when you find it, setting the selected index to that property name.
var languageSelect = $('websites1');
var oHandler = $('#websites1').msDropDown().data("dd");
for(var index = 0; index < languageSelect.length; index++) {
var option = oHandler.item([index]);
if(option == 'italian') {
oHandler.set("selectedIndex", index);
break;
}
}
One of those should work. If not, you're pretty much just going to have to wait for a reply from the author.
You can either use selectedIndex to change the index of the selected option (0 being the first)
document.getElementById("websites1").selectedIndex = 1; //espanol
, or you can use value to change the text of the value (and if there's a match, it will change it automatically).
document.getElementById("websites1").value = 'espanol';
use selectedIndex. See this page. A select control has an options property, which basically is an array of option elements. The first element in your select is options[0], english, so:
document.getElementById("websites1").selectedIndex = 0; //=> english
You can also make the first option selected by default using:
document.getElementById("websites1").options[0]
.defaultSelected = true; //=> english by default
working option (1. destroy msdropdown, 2. select by value, 3. set up msdropdown)
put this code somewhere in js:
jQuery.fn.extend({
setValue: function(value) {
var dd = $(this).msDropdown().data("dd");
dd.destroy();
$(this).val(value);
$(this).msDropdown();
}
});
setting value:
$('#selectorOfmsDropDown').setValue('opt10');
or just:
$("#selector").msDropdown().data("dd").setIndexByValue(newvalue);

jQuery addclass to each Wordpress post image

this is what I have so far:
<script>
$(document).ready(function(){
$(".entry-content img:first").addClass('postimage');
});
</script>
As you can see, for the first image of .entry-content it adds my class. Cool, that works fine. Uncool, it doesn't work for every post but only the first on the page.
I'm not sure how to fix this. Do I need to use .each in some way or is there something wrong with what I have already?
Thanks
This is because the CSS selector is selecting the first .entry-content img, not the first img in every .entry-content. It's about operator precedence.
You can iterate through each .entry-content and select the img:first in that node manually, though.
$(document).ready(function(){
var entries = document.querySelectorAll('.entry-content');
for (var i = 0; i < entries.length; i++) {
var firstImage = $(entries[i].querySelectorAll('img:first')[0]);
firstImage.addClass('postImage');
}
});
this will iterate over all your posts and apply the class to the first image within each.
$.each('.entry-content', function() {
$(this).find('img:first').addClass('postImage');
});
A variation of Paul Dragoonis' answer:
$(".entry-content").each(function ()
{
$("img:first", this).addClass("postImage");
});

Categories