NewProgrammer NewProgrammer - 5 months ago 22
Javascript Question

Using select to DOM css using attribute

Hi I am trying to display some elements using querySelectorAll to capture attributes and DOM the css for the elements, till now faced with "Syntax error: An invalid or illegal string was specified" will appreciate some help here.

Here is my code:

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8"/>
<title>select sort function</title>
<style>
a{text-decoration:none;display:none;font-family:sans-serif,arial;}
</style>
</head>
<body>
<select id="sortsel" onchange="listFunction()">
<option value='0'>- All Sorting -</option>
<option value='1'>Sort A</option>
<option value='2'>Sort B</option>
</select><br/><br/>
<div>
<a href="javascript:void(0)" data-sortid="1">Sort A sub 1</a><br/>
<a href="javascript:void(0)" data-sortid="1">Sort A sub 2</a><br/>
<a href="javascript:void(0)" data-sortid="1">Sort A sub 3</a><br/>
<a href="javascript:void(0)" data-sortid="2">Sort B sub 1</a><br/>
<a href="javascript:void(0)" data-sortid="2">Sort B sub 2</a><br/>
<a href="javascript:void(0)" data-sortid="2">Sort B sub 3</a><br/>
</div>
<script>
function listFunction(){
var selectSort = document.getElementById("sortsel");
var selectedSort = selectSort.options[selectSort.selectedIndex].value;
console.log(selectedSort);
var testing = '[';
testing += 'data-sortid="';
testing += selectedSort;
testing += '"]';
console.log(testing);
document.querySelectorAll(testing).style.display="block";
}
</script>
</body>
</html>


Much appreciate any help here.

Answer

if we want to query node attribute we may use [data-sortid='1'] like structure

Javascript

function listFunction(){
    var selectSort = document.getElementById("sortsel");
    var selectedSort = selectSort.options[selectSort.selectedIndex].value;
    console.log(selectedSort);
    var testing = '';
    testing += '[data-sortid="';
    testing += selectedSort;
    testing += '"]';
    console.log(testing);

    [].forEach.call(document.querySelectorAll(testing), function (el) {
        el.style.display="block";
    });
}