Parse HTML without IDs or classes - javascript

Is it possible to use Javascript to parse html without IDs or classes?
For example I want to delete everything from "Starting date" to "Starting time"
<div class="timer">
<!--Starting date-->
<select>
<option value="1"></option>
<option value="2"></option>
</select>
<!--Starting time-->
<select>
<option value="1"></option>
<option value="2"></option>
</select>
<!--more select tags here>
</div>

This work after making the nodelist static
let hideDate = true; // your condition
const startText = "Starting date",
endText = "Starting time";
if (hideDate) {
let i = 0;
const nodes = [...document.querySelector(".timer").childNodes]; // make list static
for (; i < nodes.length; i++) {
if (nodes[i].nodeType === 3 &&
nodes[i].textContent.trim() === startText) break;
}
for (; i < nodes.length; i++) {
if (nodes[i].nodeType === 3 &&
nodes[i].textContent.trim() === endText) break;
nodes[i].remove();
}
}
<div class="timer">
Starting date
<select>
<option value="1"></option>
<option value="2"></option>
</select>
Starting time
<select>
<option value="1"></option>
<option value="2"></option>
</select>
</div>

i think you can do something like this:
you have to select this element from javaScript for example:
var elementsContainer = document.getElementsByClassName/TagNames('element class or element tag name');
this will return you a list of elements, so you need to get one of them, like this:
elementsContainer = elementsContainer[0]
this will give you one element, so after this, you can delete its content like this
elementsContainer.innerHTML/innerText = '';
you can choose one of this property innerHTML or innerText according to which you need

Well for your problem. I would suggest to have a look at the concepts of jquery remove(), and jquery empty(). here are some working test demos of these two methods.
<script>
$(document).ready(function(){
$(".timer select").remove();
});
</script>
The above code will completely remove the elements inside the div element. see here Jquery Remove Wroking Example
<script>
$(document).ready(function(){
$(".timer").empty();
});
</script>
This method removes not only child (and other descendant) elements, but also any text within the set of matched elements
Jquery Empty Working Example
Similar to .empty(), the .remove() method takes elements out of the DOM. Use .remove() when you want to remove the element itself, as well as everything inside it.
If you want to do it with core javascript then have a look at it.
Jquery Remove method using core JS

let timer = document.querySelector('.timer')
const from = 'Starting date'
const to = 'Starting time'
let html = timer.innerHTML
timer.innerHTML = html.slice(0, html.search(from)) + html.slice(html.search(to))
<div class="timer">
Starting date
<select>
<option value="1">1</option>
<option value="2">2</option>
</select>
Starting time
<select>
<option value="1">1</option>
<option value="2">2</option>
</select>
</div>

Related

I know part of the value of a select option, I would like set that option with JS?

I would like to set an option in a select element based on the substring which will be contained in one of the option values. I have a solution but it seems quite convoluted to me.
I get the values of the options and put them in an array, loop through the values and check if the value includes a string I am looking for when it does I set that value as the select value. There must be an easier way!
I get the values of the options in the following way.
// Get the select element where you can select a procinve with a pull-down
var provincePullDown = document.querySelector(".select-provincie");
// Array containing the values of the select options
var optArray = Array.from(provincePullDown.options);
var optArrayValues = [];
optArray.forEach(el => optArrayValues.push(el.value));
I then loop over the values looking with a likely substring.
// Loop over the values in the select options
optArrayValues.forEach(function (el) {
// Look for the option containing the right province
if (el.includes(selectedProvince)) {
// Set the selected option from the select element
provincePullDown.value = el;
}
});
The option values look something like this sting (3) and the substring like this string.
I would like to know if there is an easier way as to me this seems an overly convoluted solution. And keeping maintenance in mind I would like an clear solution that I will still easily understand in 6 months.
The page is created by Drupal so I also control what html is outputted and the option values are inserted in the Drupal template.
Let me also state that I am not a fan of jQuery even though the project does load jQuery by default.
As querySelector() support any valid CSS selector, you can try with contains (*=) Attribute selector:
[attr*=value]
Represents elements with an attribute name of attr whose value contains at least one occurrence of value within the string.
var selectedProvince = 'province';
document.querySelector(".select-provincie option[value*='"+selectedProvince+"']").selected = true;
<select class="select-provincie">
<option value="prov-1">Province 1</option>
<option value="prov-2">Province 2</option>
<option value="province-test">Province 3</option>
<option value="prov-3">Province 4</option>
</select>
You can also use Template Literals for cleaner syntax:
var selectedProvince = 'province';
document.querySelector(`.select-provincie option[value*='${selectedProvince}']`).selected = true;
<select class="select-provincie">
<option value="prov-1">Province 1</option>
<option value="prov-2">Province 2</option>
<option value="province-test">Province 3</option>
<option value="prov-3">Province 4</option>
</select>
You can directly point to the option value if the regext is just a simple contain
const optToSelect = document.querySelector('option[value*=${SUBSTRING}]');
document.querySelector("select").selectedIndex = optToSelect.index;
You can use plain DOM methods with find and includes:
function updateOther(source) {
let value = source.value;
let sel = document.querySelector('.select-provincie');
sel.selectedIndex = [].find.call(sel.options, opt => opt.value.includes(value)).index;
}
<select onchange='updateOther(this)'>
<option value="1" selected>1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
</select>
<select class="select-provincie">
<option value="province1" selected>Province 1</option>
<option value="province2">Province 2</option>
<option value="province3">Province 3</option>
<option value="province4">Province 4</option>
</select>
But it's not fault tolerant: if a suitable value isn't found, it will throw an error (as do other answers). :-)
JQuery is interesting precisely when you want simplify solutions and ensure it is practical in terms of optimization. So I want to bring you a JQuery solution.
var selectedProvince = 'province3';
$(".select-provincie > option").each((index, elem) => {
if (elem.value == selectedProvince) {$(elem).attr('selected', true)};
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="select_provincie">
<select class="select-provincie">
<option value="province1">Province 1</option>
<option value="province2">Province 2</option>
<option value="province3">Province 3</option>
<option value="province4">Province 4</option>
</select>
</div>

make a select dependent with js

I would like to do a select option dependent of another select, i saw there's a way using array with fixed values, but my array is reloaded every time we add a new form field on the form. I would like something like when i select op1, then it just show op1 options on second select.
<select id="id1" name="optionshere">
<option relone="op1">opt one</option>
<option relone="op2">opt two</option>
</select>
<select id="id2" name="resulthere">
<option relone="op1">ans 1 op1</option>
<option relone="op1">ans 2 op2</option>
<option relone="op2">ans 1 op2</option>
</select>
Any idea?
thanks all
Here's a method without jQuery:
When you select an option in the first selectbox, it will hide everything that doesn't match its relone.
var id1 = document.getElementById("id1");
var id2 = document.getElementById("id2");
id1.addEventListener("change", change);
function change() {
for (var i = 0; i < id2.options.length; i++)
id2.options[i].style.display = id2.options[i].getAttribute("relone") == id1.options[id1.selectedIndex].getAttribute("relone") ? "block" : "none";
id2.value = "";
}
change();
<select id="id1" name="optionshere">
<option relone="op1">opt one</option>
<option relone="op2">opt two</option>
</select>
<select id="id2" name="resulthere">
<option relone="op1">ans 1 op1</option>
<option relone="op1">ans 2 op1</option>
<option relone="op2">ans 1 op2</option>
</select>
If Jquery is an option you may go with something like this:
<script type='text/javascript'>
$(function() {
$('#id1').change(function() {
var x = $(this).val();
$('option[relone!=x]').each(function() {
$(this).hide();
});
$('option[relone=x]').each(function() {
$(this).show();
});
});
});
</script>
Then to expand:
There really are many ways in which you can solve this predicament, depending on how variable your pool of answers is going to be.
If you're only interested in using vanilla javascript then let's start with the basics. You're going to want to look into the "onchange" event for your html, so as such:
<select onchange="myFunction()">
Coming right out of the w3schools website, on the Html onchange event attribute:
The onchange attribute fires the moment when the value of the element
is changed.
This will allow you to make a decision based on this element's value. Then inside your js may branch out from here:
You may use Ajax and pass to it that value as a get variable to obtain those options from a separate file.
You may get all options from the second div through a combination of .getElementbyId("id2") and .getElementsByTagName("option") then check for their individual "relone" attribute inside an each loop, and hide those that don't match, and show those that do.
Really, it's all up to what you want to do from there, but I personally would just go for the Jquery approach

Set HTML attribute value using java Script

I have html drop down list,which has country list. Now I want to set current country as a default value of list. I found the JavaScript code for get country using Geolocation.
My code:
function getCountry(var name) {
if(name==geoip_country_name()) {
return "selected";
}
}
Then I need to set the selected attribute of the option list.
I tried this:
<option value="Sri Lanka" selected="getCountry('sri Lanka')">Sri Lanka</option>
But this is not correct.
Basically I want to set selected attribute value using JavaScript function
How do I do that?
Use the window.onload event, and just set the dropdown's value. Keep in mind that your hard coded country names may differ from the geo service.
<script>
window.onload = function(){
document.getElementById("country").value = geoip_country_name();
}
</script>
<select id="country" name="country">
<option value="Sri Lanka">Sri Lanka</option>
<option value="UK">UK</option>
<option value="USA">USA</option>
<select>
Basically you can do it like this:
<html>
<body>
<select id="country">
<option id="germany" value="Germany">DE</option>
<option id="uk" value="UK">UK</option>
<option id="usa" value="USA">USA</option>
</select>
<script>
var selectedCountry = 'uk'; //getCountry
var index = document.getElementById(selectedCountry).index;
document.getElementById("country").selectedIndex=index;
</script>
Start the script after your select is rendered.
Note, that this example might not be best practice. I'm also not sure if it works in all browsers (Opera works). You might use an appropriate framework like JQuery, Mootools, ...
The selected attribute is not automatically evaluated as JS code. Assuming you have stored the desired country name in the variable country, could try this instead:
var country = "Sri Lanka";
var select = document.getElementById('myselect'); //Change to the ID of your select element
for (var i = 0; i < select.options.length; i++){
if(select.options[i].value == country)
select.selectedIndex = i;
}
If you are using JQuery following line should solve your problem:
$('select').val(geoip_country_name());
If geoip_country_name returns names in lower case, While initializing the select list, value for each option be in lower case.

How to modify an HTML Select when the name is an array using Javascript

I have two html select objects named with the same name (they are arrays with different indexes).
What I am trying to do, is if "off" is selected from the category[0] select element, I would like to disable the category[1] element. I have been trying to use document.getElementsByName() but am having no luck figuring out how to specifically target the category[1] array. See below for example code.
<select name='category[0]'>
<option value='0'>off</option>
<option value='1'>on</option>
</select>
<select name='category[1]'></select>
My question is how can I modify the properties of an HTML object that is an array? I understand I could do this easily using ID's but I would like to learn how to do this using an array.
Thanks
Untested:
<select name='category[0]'>
<option value='0'>off</option>
<option value='1'>on</option>
</select>
<select name='category[1]'></select>
<script>
var selects = document.getElementsByTagName('select');
for ( var i = 0, len = selects.length; i<l; ++i ) {
if ( selects[i].name == 'category[1]' ) {
// operate on selects[i];
// you can also rely on getAttribute('name')
}
}
</script>
<select name='category[0]' onChange="disCat(this.value);">
<option value='0'>off</option>
<option value='1'>on</option>
</select>
<script type="text/javascript">
function disCat(val){
if(val!="0") return;
var sels=document.getElementsByTagName("select");
for(i=0;i<sels.length;i++)
{
if(sels[i].getAttribute('name')=='category[1]') sels[i].disabled=true;
}
}
</script>

Retrieving the text of the selected <option> in <select> element

In the following:
<select id="test">
<option value="1">Test One</option>
<option value="2">Test Two</option>
</select>
How can I get the text of the selected option (i.e. "Test One" or "Test Two") using JavaScript
document.getElementsById('test').selectedValue returns 1 or 2, what property returns the text of the selected option?
function getSelectedText(elementId) {
var elt = document.getElementById(elementId);
if (elt.selectedIndex == -1)
return null;
return elt.options[elt.selectedIndex].text;
}
var text = getSelectedText('test');
If you use jQuery then you can write the following code:
$("#selectId option:selected").html();
document.getElementById('test').options[document.getElementById('test').selectedIndex].text;
Under HTML5 you are be able to do this:
document.getElementById('test').selectedOptions[0].text
MDN's documentation at https://developer.mozilla.org/en-US/docs/Web/API/HTMLSelectElement/selectedOptions indicates full cross-browser support (as of at least December 2017), including Chrome, Firefox, Edge and mobile browsers, but excluding Internet Explorer.
selectElement.options[selectElement.selectedIndex].text;
References:
options collection, selectedIndex property: HTML DOM Select Object
text property: HTML DOM Option Object
exactly the answer of this question: Option text Property
The options property contains all the <options> - from there you can look at .text
document.getElementById('test').options[0].text == 'Text One'
You can use selectedIndex to retrieve the current selected option:
el = document.getElementById('elemId')
selectedText = el.options[el.selectedIndex].text
this.options[this.selectedIndex].innerText
If you found this thread and wanted to know how to get the selected option text via event here is sample code:
alert(event.target.options[event.target.selectedIndex].text);
Use the select list object, to identify its own selected options index.
From there - grab the inner HTML of that index.
And now you have the text string of that option.
<select onchange="alert(this.options[this.selectedIndex].innerHTML);">
<option value="">Select Actions</option>
<option value="1">Print PDF</option>
<option value="2">Send Message</option>
<option value="3">Request Review</option>
<option value="4">Other Possible Actions</option>
</select>
The :checked selector can be used with document.querySelector to retrieve the selected option.
let selectedText = document.querySelector('#selectId option:checked').text;
// or
let selectedText = document.querySelector('#selectId')
.querySelector('option:checked').text;
document.querySelector('button').addEventListener('click', function(e) {
console.log(document.querySelector('#selectId option:checked').text);
});
<select id="selectId">
<option>a</option>
<option>b</option>
<option>c</option>
</select>
<button>
Get selected text
</button>
For select elements with the multiple attribute, document.querySelectorAll can be used to obtain all selected options.
let selectedText = [...document.querySelectorAll('#selectId option:checked')]
.map(o => o.text);
document.querySelector('button').addEventListener('click', function(e) {
let selectedText = [...document.querySelectorAll('#selectId option:checked')]
.map(o => o.text);
console.log(selectedText);
});
<select id="selectId" multiple>
<option>a</option>
<option>b</option>
<option>c</option>
</select>
<button>
Get selected text
</button>
Similar to #artur just without jQuery, with plain javascript:
// Using #Sean-bright's "elt" variable
var selection=elt.options[elt.selectedIndex].innerHTML;
Easy, simple way:
const select = document.getElementById('selectID');
const selectedOption = [...select.options].find(option => option.selected).text;
It is pretty simple. In javascript anything with an ID doesn't need document.queryselector or $('#test') you can just use test. Then you simply loop over the selectedOptions which is apart of javascript and you can add it to a new array and use that data how ever you want.
let selectedItems = [];
for ( var i = 0; i < test.selectedOptions.length; i++) {
selectedItems.push(test.selectedOptions[i].text);
}
Also
// if you want values
selectedItems.push(test.selectedOptions[i].value);

Categories

Resources