I have a list of divs. Each div contains a custom data attribute called "data-target". The data-target contains numbers. These numbers have nothing to do with the order.
Via Javascript I want to create a list for the right order of the divs.
For example: - Where custom attribute is "4321" set position 1. - Where custom attribute is "5849" set position 2. ...
Below you can find an example of what I am thinking of, yet it's not working.
HTML/CSS
<html>
<head>
<style>
#main {
width: 400px;
height: 100px;
border: 1px solid #000000;
display: flex;
}
#main div {
width: 70px;
height: 70px;
}
</style>
</head>
<body>
<div id="main">
<div style="background-color:green;" data-target="111222"> </div>
<div style="background-color:blue;" data-target="222333"> </div>
</div>
<button onclick="myFunction()">Try it</button>
JAVASCRIPT
<script>
function myFunction() {
$('[data-target="111222"]').style.order = "2";
$('[data-target="222333"]').style.order = "1";
}
</script>
The first div with the green background should switch to the second position. I found a working example here, but the call it by the ElementID and not a custom data attribute: https://www.w3schools.com/jsref/tryit.asp?filename=tryjsref_style_order
In your browser console you should get the following error:
Uncaught TypeError: Cannot set property 'order' of undefined
This means that jQuery object does not have a property called style
that's why it's treating it like undefined
. If you want to modify css properties of jQuery objects use .css() instead. Your code should look like:
$('div[data-target="111222"]').css('order', '2');
$('div[data-target="222333"]').css('order', '1');
Attached a Fiddle .
Try this:
function myFunction() { document.querySelector('div[data-target="111222"]').style.order = "2"; document.querySelector('div[data-target="222333"]').style.order = "1"; }
<html> <head> <style> #main { width: 400px; height: 100px; border: 1px solid #000000; display: flex; } #main div { width: 70px; height: 70px; } </style> </head> <body> <div id="main"> <div style="background-color:green;" data-target="111222"> </div> <div style="background-color:blue;" data-target="222333"> </div> </div> <button onclick="myFunction()">Try it</button>
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.